As far as I remember ArrayList should be faster on gets and slower on add and remove. Given that - could you please give me a hint what is wrong with this code if it produces completely different results: remove time is almost the same for ArrayList and LinkedList and addition is faster for ArrayList...
import java.util.ArrayList;
import java.util.LinkedList;
public class ListsTest {
public static void main(String[] args) {
ArrayList arrayList = new ArrayList();
LinkedList linkedList = new LinkedList();
// ArrayList add
long startTime = System.nanoTime();
for (int i = 0; i < 100000; i++) {
arrayList.add(i);
}
long endTime = System.nanoTime();
long duration = endTime - startTime;
System.out.println(" ArrayList add: " + duration);
// LinkedList add
startTime = System.nanoTime();
for (int i = 0; i < 100000; i++) {
linkedList.add(i);
}
endTime = System.nanoTime();
duration = endTime - startTime;
System.out.println("LinkedList add: " + duration);
// ArrayList get
startTime = System.nanoTime();
for (int i = 0; i < 10000; i++) {
arrayList.get(i);
}
endTime = System.nanoTime();
duration = endTime - startTime;
System.out.println(" ArrayList get: " + duration);
// LinkedList get
startTime = System.nanoTime();
for (int i = 0; i < 10000; i++) {
linkedList.get(i);
}
endTime = System.nanoTime();
duration = endTime - startTime;
System.out.println("LinkedList get: " + duration);
// ArrayList remove
startTime = System.nanoTime();
for (int i = 9999; i >=0; i--) {
arrayList.remove(i);
}
endTime = System.nanoTime();
duration = endTime - startTime;
System.out.println(" ArrayList remove: " + duration);
// LinkedList remove
startTime = System.nanoTime();
for (int i = 9999; i >=0; i--) {
linkedList.remove(i);
}
endTime = System.nanoTime();
duration = endTime - startTime;
System.out.println("LinkedList remove: " + duration);
}
}
My results:
ArrayList add: 13540332
LinkedList add: 93488785
ArrayList get: 676937
LinkedList get: 335366109
ArrayList remove: 529793354
LinkedList remove: 410813052
Edit: As it was mentioned in a few comments it is important whether we add/remove/get to/from the end of the list or whether we use random index. When using random index all results are "correct":
arrayList.get((int) (Math.random()*arrayList.size()));
The same issue is resolved here: https://coderanch.com/t/669483/certification/ArrayList-LinkedList-speed-comparison