LinkedList: Java Collections Framework Video Tutorial, Part 2

The second part of the tutorial series on the Java Collections Framework; in this tutorial I explain when to use LinkedList rather than ArrayList; we look at how the two classes work internally and I also explain a bit about the List interface.

After starting the video, click the maximise button to make it fullscreen so you can see the code!



Code For This Tutorial



App.java:

 
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;


public class App {


    public static void main(String[] args) {
        /*
         * ArrayLists manage arrays internally.
         * [0][1][2][3][4][5] ....
         */
        List<Integer> arrayList = new ArrayList<Integer>();
        
        /*
         * LinkedLists consists of elements where each element
         * has a reference to the previous and next element
         * [0]->[1]->[2] ....
         *    <-   <-
         */
        List<Integer> linkedList = new LinkedList<Integer>();
        
        doTimings("ArrayList", arrayList);
        doTimings("LinkedList" , linkedList);
    }
    
    private static void doTimings(String type, List<Integer> list) {
        
        for(int i=0; i<1E5; i++) {
            list.add(i);
        }
        
        long start = System.currentTimeMillis();
        
        /*
        // Add items at end of list
        for(int i=0; i<1E5; i++) {
            list.add(i);
        }
        */
        
        // Add items elsewhere in list
        for(int i=0; i<1E5; i++) {
            list.add(0, i);
        }
        
        long end = System.currentTimeMillis();
        
        System.out.println("Time taken: " + (end - start) + " ms for " + type);
    }
    


}

 
Time taken: 7546 ms for ArrayList
Time taken: 76 ms for LinkedList