ArrayList Example in Java

  • ArrayList extends AbstractList and implements the List interface.
  • ArrayList maintain the elements insertion order.
  • ArrayList is non-synchronized.
  • Default initial capacity of ArrayList is 10.
  • ArrayList allows duplicate elements.

In this example we will demonstrate mostly used methods of ArrayList.

import java.util.ArrayList;
import java.util.List;

public class ArrayListExample {
	 
    public static void main(String[] a){
         
        List<String> arrayList = new ArrayList<String>();
        
        //add elements to the list
        arrayList.add("TINA");
        arrayList.add("RAM");
        arrayList.add("JOHN");
        
        //print list elements
        System.out.println(arrayList);
        
        
        //Get the size of the list
        System.out.println("Size is: "+arrayList.size());
        
        //get elements by index
        System.out.println("Element at index 2: "+arrayList.get(2));
        
        //add elements at a specific index
        arrayList.add(2,"PLAY");
        System.out.println(arrayList);
        
        //check if list contains the specified element
        System.out.println("Contains element ALEX :"+arrayList.contains("ALEX"));
        
        //check if list it empty or not
        System.out.println("Is empty list: "+arrayList.isEmpty());
        
        //Remove element from a specific position
        arrayList.remove(1);
        
        System.out.println("After removing index 1 element : "+arrayList);
        
        //Empty the list
        arrayList.clear();
        
        System.out.println("After clearing the list: "+arrayList);

    }
}
Output
[TINA, RAM, JOHN] Size is: 3 Element at index 2: JOHN [TINA, RAM, PLAY, JOHN] Contains element ALEX :false Is empty list: false After removing index 1 element : [TINA, PLAY, JOHN] After clearing the list: []

Related Examples


Write a program to check if an input String is Palindrome or not?
Calculate the factorial of a given number using Java?
How to reverse a number in Java?
Write a program to convert from decimal to binary?
Producer Consumer Example in Thread
Write a program to reverse a String?








Receive Latest Java Examples in Your Email: