Bright Java Tutorial

is brought to you by DoITBright LLC

Java

Popular Java List Implementations

The java.util.List is an interface from the Collection API. It can grow its size and typically allows null values and duplicates. The most popular classes that implements the List are java.util.ArrayList, java.util.Vector and java.util.LinkedList. Let us look at the example code below and observe their similarities and differences.

  package com.example.core;

  import java.util.ArrayList;
  import java.util.LinkedList;
  import java.util.Vector;

  /**
   * This is to demonstrate how to use a Vector and an ArrayList.
   * It also discuss the difference between the two.
   * 
   * @author Rolan Liwanag
   *
   */
  public class LinkedListVsArrayListVsVector {

    public static void main(String[] args) {
      /*
       * You will notice below that the usage of Vector, 
       * LinkedList and ArrayList are pretty much the same.
       */
      Vector v = new Vector();
      v.add("Vector Value 1");
      v.add("Vector Value 2");
      v.add("Vector Value 3");
      for(String valueV : v) {
        System.out.println(valueV);
      }
      /*
       * Vector is from the Java Collections Framework 
       * that allows you to store objects and the size of 
       * the vector container can grow dynamically in 
       * contrast to the array which has a fixed size.
       * 
       * A Vector is synchronized. Being synchronized, 
       * this means, inherently, vector is thread safe. 
       * The trade off is, it is a little heavier which 
       * makes it a little slower.
       */
      ArrayList al = new ArrayList();
      al.add("ArrayList Value 1");
      al.add("ArrayList Value 2");
      al.add("ArrayList Value 3");
      for(String valueAl : al) {
        System.out.println(valueAl);
      }
      /*
       * Just like the Vector, an ArrayList can grow its 
       * size dynamically. An ArrayList is not 
       * synchronized which makes it not thread safe. 
       * The good thing about this is, it is fast.
       */
      LinkedList ll = new LinkedList();
      ll.add("LinkedList Value 1");
      ll.add("LinkedList Value 2");
      ll.add("LinkedList Value 3");
      for(String valueLl : ll) {
        System.out.println(valueLl);
      }
      /*
       * Just like the Vector and ArrayList, the 
       * LinkedList can grow its size dynamically. 
       * In terms of adding and removing elements in and 
       * out of the LinkedList, it is faster than the 
       * ArrayList. However, it is slower than the 
       * ArrayList in terms of reading elements in a 
       * random position than an ArrayList. To be more 
       * precise, when we access an element in a specific 
       * position using the get method.
       * 
       * Just like the ArrayList, a LinkedList is not 
       * synchronized.
       */
    }
  }
                            



Back    Next