Loading

An ArrayList is a dynamic array that implements the List interface in Java. It is part of the java.util package and provides resizable-array functionality, meaning its size automatically adjusts when elements are added or removed

Example:

Correct Use and Incorrect Use
ArrayList<int> wrongArrayList = ArrayList<int>();          // It will not work                         

ArrayList<Integer> rightArrayList = new ArrayList<Integer>(); // It will works properly


Syntax: 

Old Way and New Way

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]

 

Key Point

  • Allows Duplicate Values – Elements can be repeated in an ArrayList.
  • Index-Based Access – Elements can be accessed using an index, just like arrays.
  • Dynamic Resizing – The size grows or shrinks automatically.
  • Not Synchronized – It is not thread-safe, meaning multiple threads can modify it simultaneously.
  • Cannot Store Primitive Data Types – It stores only objects. Use wrapper classes like Integer, Double, etc., instead of int, double, etc.