I read THIS and
And understood that LinkedList add(E element) is O(1) and ArrayList add(E element) is O(1) amortized, but O(n) worst-case since the array must be resized and copied
But, when i try to check it
public class ArrayListVSLinkeedList {
public ArrayListVSLinkeedList() {
final int COUNTER = 15000000;
List<Integer> arrayList = new ArrayList<Integer>();
long tStart_add = System.currentTimeMillis();
for (int i = 0; i < COUNTER; i++) {
arrayList.add(i);
}
long tEnd_add = System.currentTimeMillis();
long tDelta_add = tEnd_add - tStart_add;
System.out.println("Adding to ArrayList: " +tDelta_add);
List<Integer> linkedList = new LinkedList<Integer>();
tStart_add = System.currentTimeMillis();
for (int i = 0; i < COUNTER; i++) {
linkedList.add(i);
}
tEnd_add = System.currentTimeMillis();
tDelta_add = tEnd_add - tStart_add;
System.out.println("Adding to LinkedList: " +tDelta_add);
}
public static void main(String[] args) {
new ArrayListVSLinkeedList();
}
}
I received at output:
Adding to ArrayList: 9122
Adding to LinkedList: 19859
I know, this is not real benchmark, but... Finally, adding element to the end of ArrayList is faster then to LinkedList. Why this happens?