Image

Java - Core Java - Collection Framework - List(I) - ArrayList

List (I)

It is a child interface of collection. If we want to represent a group of individual objects as a single entity where duplicates are allowed and the insertion order must be preserved then we should go for List.

we can preserve insertion order via. index and we can differentiate duplicate objects by using index. Hence index will play a very important role in List.

ArrayList

ArrayList is a part of collection framework and is present in java.util package. It provides us dynamic arrays in Java. Though, it may be slower than standard arrays but can be helpful in programs where lots of manipulation in the array is needed.

  • Resizable array or growable array.
  • Duplicates are allowed.
  • Insertion order preserved.
  • Heterogeneous objects are allowed
  • Null insertion is possible.
  • For Example
    import java.util.ArrayList;
    public class ArrayListDemo 
    {
     public static void main(String[] args) 
     {
            ArrayList al=new ArrayList();
            al.add("A");
            al.add(10);
            al.add("A");
            al.add(null);
            System.out.println(al);
            al.remove(2);
            System.out.println(al);
            al.add(2, "M");
            al.add("N");
            System.out.println(al);
            al.removeAll(al);
            System.out.println(al);
    //      al.add(3, "C");  // java.lang.IndexOutOfBoundsException: Index: 3, Size: 0
    //      System.out.println(al);
        }
    }   
    O/P
    [A, 10, A, null]
    [A, 10, null]
    [A, 10, M, null, N]
    []
    

    ArrayList is the best choice if our frequent operation is retrieval operation, because ArrayList implements RandomAccess interface.

    ArrayList is the worst choice if our frequent operation is insertion or deletion in the middle.