Arraylist class implements List interface. It is widely used because of the functionality and flexibility it offers. Most of the developers choose Arraylist over Array as it’s a very good alternative of traditional java arrays. ArrayList is a resizable-array implementation of the List interface. It implements all optional list operations, and permits all elements, including null. ArrayList can dynamically grow and shrink after addition and removal of elements. The important points about Java ArrayList class are:

  • It can contain duplicate elements.
  • It maintains insertion order.
  • It is non synchronized.
  • It allows random access because array works at the index basis.
  • In Java ArrayList class, manipulation is slow because a lot of shifting needs to be occurred if any element is removed from the array list.

Methods of ArrayList class

  • add( Object o): This method adds an object o to the arraylist.
  • add(int index, Object o): It adds the object o to the array list at the given index.
  • remove(Object o): Removes the object o from the ArrayList.
  • remove(int index): Removes element from a given index.
  • set(int index, Object o): Used for updating an element. It replaces the element present at the specified index with the object o.
  • int indexOf(Object o): Gives the index of the object o. If the element is not found in the list then this method returns the value -1.
  • Object get(int index): It returns the object of list which is present at the specified index.
  • int size(): It gives the size of the ArrayList – Number of elements of the list.
  • boolean contains(Object o): It checks whether the given object o is present in the array list if its there then it returns true else it returns false.
  • clear(): It is used for removing all the elements of the array list in one go.

Example :-

import java.util.*; 
 class TestCollection{ 
 public static void main(String args[]){ 
   ArrayList<String> al=new ArrayList<String>();   
   al.add("R"); 
   al.add("V"); 
   al.add("A"); 
 
  Iterator itr=al.iterator(); 
  
  while(itr.hasNext()){ 
    System.out.println(itr.next()); 
  } 
 } 
}