Let’s demonstrate these differences by actually measuring the time it takes to complete an operation: adding elements to a list.
Here is our test code:
long a, b;
LinkedList<Integer> list1 = new LinkedList<Integers>();
a = System.nanoTime();
for(int i=0; i<10000; i++)
list1.add(1);
b = System.nanoTime();
System.out.println("Linked: " + (b-a) + " ns");
ArrayList<Integer> list2 = new ArrayList<Integer>();
a = System.nanoTime();
for(int i=0; i<10000; i++)
list2.add(1);
b = System.nanoTime();
System.out.println("ArrayList: " + (b-a) + " ns");
System.nanoTime() is a method which returns the current time of the system in nanoseconds. We record the time and store it in a, complete our operation, and then record the time again to store it in b. (a and b are longs because the current time in nanoseconds is too large to fit in an integer.)
We add a large number of elements (10,000) because the efficiency differences usually only show up when dealing with large amounts of data. We just add the element “1” repeatedly for simplicity.
Here is the output:
Linked: 10251960 ns
ArrayList: 18086990 ns