Understanding ArrayList in Java (With Examples)

ArrayList in Java

ArrayList provides the dynamic array for storing the elements. ArrayList is a class in Java collection framework.It comes under java.util package.

Need for ArrayList: We use ArrayList when we need to do lot of modifications to the elements.

Feature of ArrayList:

1)ArrayList is similar to Array but there is no limit on size of elements which can be stored in it.

2)ArrayList can have duplicate elements too.

3)ArrayList maintains the insertion order so while reading/retrieving you will get the elements in the order you stored the elements.

4)ArrayList is non synchronized.

Pros/cons of using ArrayList over Arrays:

If we compare it with Arrays then main advantage is we do not need to specify the size of elements in ArrayList while declaring it,but in Arrays we need to initialise the size upfront during declaration itself.

On the other side, ArrayList is slower than Arrays.

It is an implementation class of List interface in util package.

Example:

import java.util.*;  
 public class ArrayListExample1{  
 public static void main(String args[]){  
  ArrayList list=new ArrayList();//Create arraylist   object
//Adding object to arraylist    
      list.add("Hyundai");
      list.add("Toyota");    
      list.add("Maruti");    
      list.add("Cruiser");    
      //Printing the arraylist elements   
      System.out.println(list);  
 }  
}      

Leave a comment