Loading

ArrayList

  • ArrayList implements the List interface.
  • It is available in java.util package.
  • It can have duplicate values.
  • We can add and remove elements at any place in ArrayList and it will adjust its size automatically that’s why it is also known as a dynamic array.
  • It is not synchronized.
  • ArrayList of the primitive types can not be created.
ArrayList<int> wrongArrayList = ArrayList<int>();          // It will not work                         
ArrayList<Integer> rightArrayList = 
new ArrayList<Integer>();                            // It will works properly  

Syntax: 

ArrayList list = new ArrayList();                             // Old ways
ArrayList<Integer> list = new ArrayList<Integer>();             // New ways

Example:

import java.util.*;
public class Array_List 
{
	public static void main(String[] args) 
	{
		ArrayList animal = new ArrayList();   
	    animal.add("Cow");  
	    animal.add("Dog");    
	    animal.add("Cat");    
	    animal.add("Lion");      
	    System.out.println(animal); 
	}
}

Output: 

[Cow, Dog, Cat, Lion]