Java ArrayList Tutorial

The tutorial explains everything about ArrayList in Java. Learn how to use Java ArrayList methods and properties.

Java ArrayList 

 
The array is a collection of elements of the same data type, stored in a contiguous memory location. A list is a non-linear collection of data where the data stored can be of different types, and also, the data is stored in non-contiguous memory locations.
 
An array has a hardcoded limit, i.e., the size of an array is always predefined which can't be increased dynamically. A list, on the other hand, has a variable limit, i.e., the size of a list can be increased dynamically.
 
ArrayList in Java is the list of array. An ArrayList combines the properties of List and of an Array, i.e., in ArrayList, the size is varied dynamically at runtime which also indicates that instead of a stack, a heap is used.
 
Java is completely an object-oriented language, hence everything in Java is a class. And each class is stored in a given package. The ArrayList class is stored in the java.util package. 
 
The method to use and implement ArrayList Class has been demonstrated below.     
  1. public class Csharpcorner           
  2. {          
  3.   public static void main(String[] args)           
  4.   {  
  5.     ArrayList<String> cars = new ArrayList<String>(); // Create an ArrayList object           
  6.    }  
  7. }  
In the above code, we are creating an object of ArrayList class. The above array list will store all the elements as String.
 

ArrayList Constructors 

  1. Arraylist.ArrayList()
    Used to build an empty ArrayList.
    1. public class Csharpcorner             
    2. {            
    3.   public static void main(String[] args)             
    4.   {    
    5.     ArrayList cars = new ArrayList(); // Create an ArrayList object             
    6.    }    
    7. }    
  2. Arraylist.ArrayList<Collection c>()
    This constructor is used to build an ArrayList initialized with the elements from the collection c.
    1. import java.util.ArrayList;  
    2. public class Csharpcorner               
    3. {              
    4.   public static void main(String[] args)               
    5.   {      
    6.     ArrayList<String> cars = new ArrayList<String>(); // Create an ArrayList object               
    7.    }      
    8. }      
  3. ArrayList(int capacity)
    This constructor is used to build an ArrayList with initial capacity being specified.
    1. import java.util.ArrayList; // import the ArrayList class                 
    2.                 
    3. public class Csharpcorner           
    4. {          
    5.   public static void main(String[] args)           
    6.   {  
    7.     int capacity=6//defines initial capacity    
    8.     ArrayList<String> cars = new ArrayList<String>(capacity); // Create an ArrayList object     
    9.    }  

Features of ArrayList

  1. The ArrayList class has predefined some methods to access and modify ArrayList Elements.
  2. Size of an ArrayList can be increased or decreased whenever needed.
  3. ArrayList only supports object entries, not the primitive data types.
  4. In ArrayList, the actual objects are never stored at contiguous locations. References of the actual objects are stored at contiguous locations. 

ArrayList Methods

  1.  Arraylist.add()

    Syntax

    a. void add(int index, E element)
    This version of the method inserts the specified element E at the specified position in this list. It shifts the element currently at that position (if any) and any subsequent elements to the right (will add one to their indices).

    b. boolean add(E e)
    This version of the method appends the specified element to the end of this list.
    1. import java.util.ArrayList; // import the ArrayList class          
    2.      
    3. public class Csharpcorner     
    4. {    
    5.   public static void main(String[] args)     
    6.   {    
    7.     ArrayList<String> cars = new ArrayList<String>(); // Create an ArrayList object          
    8.       
    9.     cars.add("Ford")  ;    
    10.    }
    11. }    
    This code will add "Ford" as the first element of the String ArrayList, i.e. now the size of has increased to one which was initially zero. In the same way.

  2. Arraylist.addAll()

    Syntax

    a. boolean addAll(Collection c)
    This version of AddAll() is used to append all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's iterator.

    b. boolean addAll(int index, Collection c)
    This version of AddAll() is used to append all the elements in the specified collection, starting at the specified position of the list.
    1. import java.util.ArrayList; // import the ArrayList class             
    2.     
    3. public class Csharpcorner       
    4. {      
    5.   public static void main(String[] args)       
    6.   {      
    7.     ArrayList<String> cars = new ArrayList<String>(); // Create an ArrayList object            
    8.         
    9.     cars.add("Ford")  ;      
    10.     cars.add("Ferrari");      
    11.     cars.add("Maruti");      
    12.     cars.add("Vokesvagen");      
    13.       
    14.     ArrayList<String> new_cars = new ArrayList<String>();    
    15.       
    16.     new_cars.add("Bukati");      
    17.       
    18.     new_cars.addAll(cars);  
    19.    }  
    20. }      
    In the above program, we are creating two ArrayLists with name cars and new_cars respectively. And then we will copy all the elements of cars into new_cars.

  3. Arraylist.clear()

    Syntax

    void clear()
    It is used to remove all of the elements from this list.
    1. import java.util.ArrayList; // import the ArrayList class             
    2.   
    3. public class Csharpcorner       
    4. {      
    5.   public static void main(String[] args)       
    6.   {      
    7.     ArrayList<String> cars = new ArrayList<String>(); // Create an ArrayList object            
    8.         
    9.     cars.add("Ford")  ;      
    10.     cars.add("Ferrari");      
    11.     cars.add("Maruti");      
    12.     cars.add("Vokesvagen");      
    13.     
    14.     cars.clear();
    15.    }  
    16. }  
    In the above code, the clear Method will delete all the inserted values for the ArrayList cars

  4. Arraylist.ensureCapacity()

    Syntax

    void ensureCapacity(int requiredCapacity)
    1. import java.util.ArrayList; // import the ArrayList class               
    2. public class Csharpcorner         
    3. {        
    4.   public static void main(String[] args)         
    5.   {        
    6.     ArrayList<String> cars = new ArrayList<String>(); // Create an ArrayList object    
    7.     ArrayList<String> cars = new ArrayList<String>(); // Create an ArrayList object              
    8.           
    9.     cars.add("Ford")  ;        
    10.     cars.add("Ferrari");        
    11.     cars.add("Maruti");        
    12.     cars.add("Vokesvagen");       
    13.     
    14.     cars.ensureCapacity(5000);    
    15.    }  
    16. }  
    The above code will make sure that cars can hold up to 5000 elements.

  5. Arraylist.Get()

    Syntax

    E get(int index)
    1. import java.util.ArrayList; // import the ArrayList class                 
    2.                
    3. public class Csharpcorner           
    4. {          
    5.   public static void main(String[] args)           
    6.   {           
    7.     ArrayList<String> cars = new ArrayList<String>(); // Create an ArrayList object
    8.     cars.add("Ford")  ;          
    9.     cars.add("Ferrari");          
    10.     cars.add("Maruti");          
    11.     cars.add("Vokesvagen");       
    12.     
    13.     String c = cars.get(2);   
    14.    }  
    15. }  
    The above code will fetch the third element i.e. "Maruti" from cars

  6. Arraylist.isEmpty()

    Syntax

    boolean isEmpty()
    It returns true if the list is empty, otherwise false.
    1. import java.util.ArrayList; // import the ArrayList class                              
    2.   
    3. public class Csharpcorner           
    4. {          
    5.   public static void main(String[] args)           
    6.   {           
    7.     ArrayList<String> cars = new ArrayList<String>(); // Create an ArrayList object
    8.     cars.add("Ford")  ;          
    9.     cars.add("Ferrari");          
    10.     cars.add("Maruti");          
    11.     cars.add("Vokesvagen");       
    12.     
    13.     ans=cars.isEmpty();    
    14.     
    15.     if(ans==true)    
    16.             System.out.println("it is empty");    
    17.     else    
    18.             System.out.println("It is not empty");        
    19.    }  
    20. }  
    The above code will check whether the ArrayList cars is empty or not. If it is empty then it will print "It is empty".

  7. Arraylist.LastIndexOf()

    Syntax

    int lastIndexOf(Object o)
    It is used to return the index in this list of the last occurrence of the specified element, or -1 if the list does not contain this element.
    1. import java.util.ArrayList; // import the ArrayList class                             
    2.   
    3. public class Csharpcorner           
    4. {          
    5.   public static void main(String[] args)           
    6.   {           
    7.     ArrayList<String> cars = new ArrayList<String>(); // Create an ArrayList object
    8.     cars.add("Ford")  ;          
    9.     cars.add("Ferrari");          
    10.     cars.add("Maruti");          
    11.     cars.add("Vokesvagen");       
    12.     
    13.     int element = arr.lastIndexOf("Maruti");     
    14.     if (element != -1)     
    15.             System.out.println("the lastIndexof of" +      
    16.                              " Maruti is " + element);     
    17.     else    
    18.             System.out.println("Maruti is not present in" + " the list");          
    19.    }  
    20. }  
    The above code will check the latest occurrence of the element "Maruti", and returns the integer index

  8. Arraylist.toArray()

    Syntax

    a.    Object[] toArray()
    b.    <T> T[] toArray(T[] a)
    It is used to return an array containing all of the elements in this list in the correct order.
    1. import java.util.ArrayList; // import the ArrayList class                              
    2.   
    3. public class Csharpcorner           
    4. {          
    5.   public static void main(String[] args)           
    6.   {           
    7.     ArrayList<String> cars = new ArrayList<String>(); // Create an ArrayList object
    8.     cars.add("Ford")  ;          
    9.     cars.add("Ferrari");          
    10.     cars.add("Maruti");          
    11.     cars.add("Vokesvagen");       
    12.     
    13.     Object[] objects = cars.toArray();   
    14.    }  
    15. }    
    The above code will convert the ArrayList object into an array of type Object

  9. Arraylist.clone()

    Syntax

    Object clone()
    It is used to return a shallow copy of an ArrayList.
    1. import java.util.ArrayList; // import the ArrayList class                 
    2.                 
    3. public class Csharpcorner           
    4. {          
    5.   public static void main(String[] args)           
    6.   {  
    7.     ArrayList<String> cars = new ArrayList<String>(); // Create an ArrayList object           
    8.     cars.add("Ford")  ;          
    9.     cars.add("Ferrari");          
    10.     cars.add("Maruti");          
    11.     cars.add("Vokesvagen");       
    12.     
    13.     ArrayList<String> new_cars = new ArrayList<String(); // Create an ArrayList object                
    14.     
    15.     new_cars = cars.clone();     
    16.    }  
    17. }  
    A shallow copy means that when we are creating a copy we are not assigning memory to the new copy, instead of that we are using the new copy as a pointer to which we pass the address of the original ArrayList.

    So in the above code, we are passing the address of cars to new_cars

  10. Arraylist.contains()

    Syntax

    boolean contains(Object o)
    It returns true if the list contains the specified element
    1. import java.util.ArrayList; // import the ArrayList class                 
    2.                 
    3. public class Csharpcorner           
    4. {          
    5.   public static void main(String[] args)           
    6.   {  
    7.     ArrayList<String> cars = new ArrayList<String>(); // Create an ArrayList object           
    8.     cars.add("Ford")  ;          
    9.     cars.add("Ferrari");          
    10.     cars.add("Maruti");          
    11.     cars.add("Vokesvagen");       
    12.     
    13.     boolean ans = arr.contains("Ford");     
    14.       
    15.     if (ans)     
    16.            System.out.println("The list contains Ford");     
    17.     else    
    18.            System.out.println("The list does not contain Ford");       
    19.    }  
    20. }  
    In the above code, we are checking for the presence of "Ford". If we can find it in the ArrayList cars, we print "the list contains Ford" otherwise we print "The list does not contain Ford."

  11. Arraylist.indexOf()

    Syntax

    int indexOf(Object o)
    It is used to return the index in this list of the first occurrence of the specified element, or -1 if the List does not contain this element.
    1. import java.util.ArrayList; // import the ArrayList class                 
    2.                 
    3. public class Csharpcorner           
    4. {          
    5.   public static void main(String[] args)           
    6.   {  
    7.     ArrayList<String> cars = new ArrayList<String>(); // Create an ArrayList object           
    8.     cars.add("Ford")  ;          
    9.     cars.add("Ferrari");          
    10.     cars.add("Maruti");          
    11.     cars.add("Vokesvagen");       
    12.     
    13.     boolean ans = arr.contains("Ford");     
    14.       
    15.     int element = arr.indexOf("Maruti");       
    16.     if (element != -1)       
    17.             System.out.println("the indexof of" +        
    18.                              " Maruti is " + element);       
    19.     else      
    20.             System.out.println("Maruti is not present in" + " the list");      
    21.    }  
    22. }  
    The above code will check the least recent occurrence of the element "Maruti", and returns the integer index

  12. Arraylist.remove()

    Syntax

    1. E remove(int index)
    It is used to remove the element present at the specified position in the list.

    2. boolean remove(Object o)
    It is used to remove the first occurrence of the specified element.
    1. import java.util.ArrayList; // import the ArrayList class                 
    2.                 
    3. public class Csharpcorner           
    4. {          
    5.   public static void main(String[] args)           
    6.   {  
    7.     ArrayList<String> cars = new ArrayList<String>(); // Create an ArrayList object           
    8.     cars.add("Ford")  ;          
    9.     cars.add("Ferrari");          
    10.     cars.add("Maruti");          
    11.     cars.add("Vokesvagen");       
    12.     
    13.     boolean ans = arr.contains("Ford");     
    14.       
    15.     cars.remove(2);    
    16.     cars.remove("Ford");     
    17.    }  
    18. }  
    In the above code, first, we delete "Maruti" and "Ford" from ArrayList cars

  13. Arraylist.removeAll()

    Syntax

    boolean removeAll(Collection<?> c)
    It is used to remove all the elements from the list.
    1. import java.util.ArrayList; // import the ArrayList class                 
    2.                 
    3. public class Csharpcorner           
    4. {          
    5.   public static void main(String[] args)           
    6.   {  
    7.     ArrayList<String> cars = new ArrayList<String>(); // Create an ArrayList object           
    8.     cars.add("Ford")  ;          
    9.     cars.add("Ferrari");          
    10.     cars.add("Maruti");          
    11.     cars.add("Vokesvagen");       
    12.     
    13.     boolean ans = arr.contains("Ford");     
    14.       
    15.     cars.removeAll(cars);       
    16.    }  
    17. }  
    In the above, we will remove the whole of the ArrayList cars

    Note
    clear() is faster than that of remove()

  14. Arraylist.removeIf()

    Syntax
    boolean removeIf(Predicate<? super E> filter)
    It is used to remove all the elements from the list that satisfies the given predicate.
    1. import java.util.ArrayList; // import the ArrayList class                 
    2.                 
    3. public class Csharpcorner           
    4. {          
    5.   public static void main(String[] args)           
    6.   {  
    7.     ArrayList<String> cars = new ArrayList<String>(); // Create an ArrayList object           
    8.     cars.add("Ford")  ;          
    9.     cars.add("Ferrari");          
    10.     cars.add("Maruti");          
    11.     cars.add("Vokesvagen");       
    12.     
    13.     boolean ans = arr.contains("Ford");     
    14.           
    15.     cars.removeIf(n -> (n ==" Maruti"));     
    16.    }  
    17. }  
    In the above code, we are removing all the occurrences of "Maruti" from the ArrayList cars.
                
  15. Arraylist.removeRange()

    Syntax

    protected void removeRange(int fromIndex, int toIndex)
    It is used to remove all the elements lies within the given range.
    1. import java.util.ArrayList; // import the ArrayList class                 
    2.                 
    3. public class Csharpcorner           
    4. {          
    5.   public static void main(String[] args)           
    6.   {  
    7.     ArrayList<String> cars = new ArrayList<String>(); // Create an ArrayList object           
    8.     cars.add("Ford")  ;          
    9.     cars.add("Ferrari");          
    10.     cars.add("Maruti");          
    11.     cars.add("Vokesvagen");       
    12.     
    13.     boolean ans = arr.contains("Ford");     
    14.           
    15.     cars.removeRange(02)    
    16.    }  
    17. }  
    In the above code, we are removing the first 2 elements i.e "Ford" and "Ferrari"

  16. Arraylist.replaceAll()

    Syntax

    void replaceAll(UnaryOperator<E> operator)
    It is used to replace all the elements from the list with the specified element.
    1. import java.util.ArrayList; // import the ArrayList class                 
    2.   
    3. import java.util.function.*;  
    4.   
    5. class MyOperator<T> implements UnaryOperator<T>  
    6. {  
    7.     T varc1;  
    8.     public T apply(T varc)  
    9.     {  
    10.         return varc1;  
    11.     }  
    12. }  
    13.                 
    14. public class Csharpcorner           
    15. {          
    16.   public static void main(String[] args)           
    17.   {  
    18.     ArrayList<String> cars = new ArrayList<String>(); // Create an ArrayList object           
    19.     MyOperator<String> operator;  
    20.     
    21.     operator = new MyOperator<> ();  
    22.       
    23.     cars.add("Ford")  ;          
    24.     cars.add("Ferrari");          
    25.     cars.add("Maruti");          
    26.     cars.add("Vokesvagen");       
    27.     
    28.     operator.varc1 = "Ambassodor";  
    29.       
    30.     cars.replaceAll(operator);  
    31.    }  
    32. }  
    In the above code, we replace "Ford", "Ferarri", "Maruti" and "Volkswagen" with "Ambassador" i.e. the whole of the ArrayList cars will contain only "Ambassador"

  17. Arraylist.retainAll()

    Syntax

    void retainAll(Collection<?> c)
    It is used to retain all the elements in the list that are present in the specified collection.
    1. import java.util.ArrayList; // import the ArrayList class                 
    2.                 
    3. public class Csharpcorner           
    4. {          
    5.   public static void main(String[] args)           
    6.   {   
    7.        ArrayList<String> cars = new ArrayList<String>(capacity); // Create an ArrayList object     
    8.        cars.add("Ford")  ;            
    9.        cars.add("Ferrari");            
    10.        cars.add("Maruti");            
    11.        cars.add("Vokesvagen");     
    12.       
    13.        ArrayList<String> new_cars = new ArrayList<String>();   
    14.     
    15.         // Add values in the boxes list.   
    16.        new_cars.add("Ford");   
    17.        new_cars.add("Ferari");   
    18.        new_cars.add("Mecedes");   
    19.        new_cars.add("Benz");   
    20.   
    21.        new_cars.retainAll(cars);  
    22.    }  
    23. }  
    In the above code, we will be removing "Mercedes" and "Benz" from ArrayList new_cars as these two values are not present in ArrayList cars.

  18. Arraylist.set()

    Syntax

    E set(int index, E element)
    It is used to replace the specified element in the list, present at the specified position.
    1. import java.util.ArrayList; // import the ArrayList class                 
    2.                 
    3. public class Csharpcorner           
    4. {          
    5.   public static void main(String[] args)           
    6.   {   
    7.        ArrayList<String> cars = new ArrayList<String>(); // Create an ArrayList object     
    8.        cars.add("Ford")  ;            
    9.        cars.add("Ferrari");            
    10.        cars.add("Maruti");            
    11.        cars.add("Vokesvagen");     
    12.       
    13.        cars.set(,"Benz");  
    14.    }  
    15. }  
    In the above code, we are replacing the 3rd element values to "Benz", i.e. "Maruti" will be replaced with "Benz".

  19. Arraylist.sort()

    Syntax

    void sort(Comparator<? super E> c)
    It is used to sort the elements of the list based on the specified comparator.
    1. import java.util.ArrayList; // import the ArrayList class                 
    2. import java.util.Collections.sort() //import the Collections class  
    3.                 
    4. public class Csharpcorner           
    5. {          
    6.   public static void main(String[] args)           
    7.   {   
    8.        ArrayList<String> cars = new ArrayList<String>(); // Create an ArrayList object     
    9.        cars.add("Ford")  ;            
    10.        cars.add("Ferrari");            
    11.        cars.add("Maruti");            
    12.        cars.add("Vokesvagen");     
    13.       
    14.        Collections.sort(cars);  
    15.    }  
    16. }  
    In above the code, we will be sorting the above list according to the ASCII value as the ArrayList is of String Collection type, i.e. "Ferrari", "Ford", "Maruti", "Volkswagen"

  20. Arraylist.spliterator()

    Syntax

    Spliterator<E> spliterator()
    It is used to create spliterator over the elements in a list.
    1. import java.util.ArrayList; // import the ArrayList class                  
    2.                 
    3. public class Csharpcorner           
    4. {          
    5.   public static void main(String[] args)           
    6.   {   
    7.        ArrayList<String> cars = new ArrayList<String>(); // Create an ArrayList object     
    8.        cars.add("Ford")  ;            
    9.        cars.add("Ferrari");            
    10.        cars.add("Maruti");            
    11.        cars.add("Vokesvagen");     
    12.       
    13.        Spliterator<String> new_cars = cars.spliterator();   
    14.    }  
    15. }  
    In the above code, we have created a Spliterator named new_cars from the ArrayList cars.

  21. Arraylist.subList()

    Syntax

    List<E> subList(int fromIndex, int toIndex)
    It is used to fetch all the elements lies within the given range.
    1. import java.util.ArrayList; // import the ArrayList class                 
    2.                  
    3. public class Csharpcorner           
    4. {          
    5.   public static void main(String[] args)           
    6.   {   
    7.        ArrayList<String> cars = new ArrayList<String>(); // Create an ArrayList object     
    8.        cars.add("Ford")  ;            
    9.        cars.add("Ferrari");            
    10.        cars.add("Maruti");            
    11.        cars.add("Vokesvagen");     
    12.       
    13.        ArrayList<String> new_cars = cars.subList(1, 3);    
    14.    }  
    15. }  
    In the above code, we are creating a ArrayList new_cars which contains the values "Ferrari" and "Maruti".

  22. Arraylist.size()

    Syntax

    int size()
    It is used to return the number of elements present in the list.
    1. import java.util.ArrayList; // import the ArrayList class                 
    2.                 
    3. public class Csharpcorner           
    4. {          
    5.   public static void main(String[] args)           
    6.   {   
    7.        ArrayList<String> cars = new ArrayList<String>(); // Create an ArrayList object     
    8.        cars.add("Ford")  ;            
    9.        cars.add("Ferrari");            
    10.        cars.add("Maruti");            
    11.        cars.add("Vokesvagen");     
    12.       
    13.        int size= cars.size();   
    14.    }  
    15. }  
    In the above code, we are finding the number of elements that are present in ArrayList cars

  23. Arraylist.trimToSize()

    Syntax

    void trimToSize()
    It is used to trim the capacity of this ArrayList instance to be the list's current size.
    1. import java.util.ArrayList; // impo rt the ArrayList class                 
    2.                 
    3. public class Csharpcorner           
    4. {          
    5.   public static void main(String[] args)           
    6.   {   
    7.        int capacity=20;  
    8.        ArrayList<String> cars = new ArrayList<String>(capacity); // Create an ArrayList object     
    9.        cars.add("Ford")  ;            
    10.        cars.add("Ferrari");            
    11.        cars.add("Maruti");            
    12.        cars.add("Vokesvagen");     
    13.       
    14.        cars.trimToSize();   
    15.    }  
    16. }  
    In the above code, we will be reducing the size of ArrayList cars from 20 to 4 (i.e., current ArrayList size)

Conclusion

 
In this article, we learned about ArrayList, the difference between Array and List, features of ArrayList, ArrayList Methods, and how to use ArrayList Class and Methods using Java.
 
Next Tutorial in this Series >>Java Array