Java Utility Library

Java ArrayList - addAll() Method



The java.util.ArrayList.addAll() method is used to append all elements of the specified collection at the end of the ArrayList. The order of the appended element will be the same as returned by the specified collection's Iterator. This method should not be called while the specified collection is modified. This may cause undefined behavior and return wrong result.

Syntax

public boolean addAll(Collection<? extends E> c)

Here, E is the type of element maintained by the container.


Parameters

c Specify the collection containing all elements which need to be added in the ArrayList.

Return Value

Returns true if the ArrayList changed as a result of the call, else returns false.

Exception

Throws NullPointerException, if the specified collection is null.

Example:

In the example below, the java.util.ArrayList.addAll() method is used to append all elements of the ArrayList Arr2 at the end of ArrayList Arr1.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a ArrayList
    ArrayList<Integer> Arr1 = new ArrayList<Integer>();
    ArrayList<Integer> Arr2 = new ArrayList<Integer>();

    //populating Arr1 
    Arr1.add(10);
    Arr1.add(20);
    Arr1.add(30);

    //populating Arr2 
    Arr2.add(100);
    Arr2.add(200);

    //printing ArrayList
    System.out.println("Before method call, Arr1 contains: " + Arr1); 

    //appending all elements of Arr2 into Arr1
    Arr1.addAll(Arr2);
    
    //printing ArrayList
    System.out.println("After method call, Arr1 contains: " + Arr1);      
  }
}

The output of the above code will be:

Before method call, Arr1 contains: [10, 20, 30]
After method call, Arr1 contains: [10, 20, 30, 100, 200]

❮ Java.util - ArrayList