You should be running these tests in separate methods as the optimisation of the first loop can interfere with the optimisation of the second i.e. the second one can be slower, just because it is second.
I suggest you run both tests at least 10 (or for 2 seconds) and use System.nanoTime() which has higher resolution.
If you do this and you still run out of memory I suggest you increase the maximum memory size. If you are running 32-bit windows, the default is very low. You can increase it with -Xmx1g
on the command line
If you run the following, you can see that GCs have the biggest impact which is not surprising as the problem most produces garbage
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public class Collectionss {
public static final int TO_ADD = 10000000;
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
long timeAL = timeAddToArrayList();
long timeLL = timeAddsToLinkedList();
System.out.printf("Time to add %,d Integer to ArrayList %.3f sec, LinkedList %.3f%n",
TO_ADD, timeAL / 1e9, timeLL / 1e9);
}
}
private static long timeAddToArrayList() {
long starttime = System.nanoTime();
List<Integer> l1 = new ArrayList<Integer>();
for (int i = 1; i <= TO_ADD; i++) {
l1.add(i);
}
assert TO_ADD == l1.size();
return System.nanoTime() - starttime;
}
private static long timeAddsToLinkedList() {
long starttime = System.nanoTime();
List<Integer> l2 = new LinkedList<Integer>();
for (int i = 1; i <= TO_ADD; i++) {
l2.add(i);
}
assert TO_ADD == l2.size();
return System.nanoTime() - starttime;
}
}
prints
Time to add 10,000,000 Integer to ArrayList 0.238 sec, LinkedList 1.326
Time to add 10,000,000 Integer to ArrayList 1.193 sec, LinkedList 0.971
Time to add 10,000,000 Integer to ArrayList 0.841 sec, LinkedList 0.048
Time to add 10,000,000 Integer to ArrayList 0.349 sec, LinkedList 1.128
Time to add 10,000,000 Integer to ArrayList 0.064 sec, LinkedList 0.048
However add System.gc() before each test and you get
Time to add 10,000,000 Integer to ArrayList 0.241 sec, LinkedList 2.130
Time to add 10,000,000 Integer to ArrayList 0.070 sec, LinkedList 0.072
Time to add 10,000,000 Integer to ArrayList 0.067 sec, LinkedList 0.053
Time to add 10,000,000 Integer to ArrayList 0.069 sec, LinkedList 0.048
Time to add 10,000,000 Integer to ArrayList 0.065 sec, LinkedList 0.051