Wednesday 3 August 2011

Difference between LinkedList and ArrayList (Java)

As we can see from the definition of the two: 
 
public class ArrayList<E>
extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, Serializable

public class LinkedList<E>
extends AbstractSequentialList<E>
implements List<E>, Queue<E>, Cloneable, Serializable

ArrayList is a FIFO implementation and it is also indexed 
(implements RandomAccess) so it is better for the situations 
when we want to read the data in the random order and when 
the elements are added at the end of the list. But the same
implementation i.e. ArrayList is not good for the situations 
when we want to insert the elements in between because all the 
elements coming after the inserted element has to be shifted.
Similarly, LinkedList is better option when adding the elements in 
between and scales up in a better way.
 
Anyways, both are the internal implementation of java. So you won't
 find the bigger difference in terms of performance, if you are 
using these two for small programs. The performance and other issues
 come into picture when the complexity and data set increases.