Java ArrayList - addAll() Method
The java.util.ArrayList.addAll() method is used to insert all elements of the specified collection at the specified position in the ArrayList. The method shifts the current element at the specified position (if any) and any subsequent elements to the right (increases their indices). The new elements will appear in the ArrayList in the order that they are returned by the specified collection's iterator.
Syntax
public boolean addAll(int index, Collection<? extends E> c)
Here, E is the type of element maintained by the container.
Parameters
index |
Specify index number at which the first element of collection need to be inserted in the ArrayList. |
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 IndexOutOfBoundsException, if the index is out of range i.e., (index < 0 || index > size()).
Throws NullPointerException, if the specified collection is null.
Example:
In the example below, the java.util.ArrayList.addAll() method is used to insert all elements of the ArrayList arr at the specified position in the ArrayList MyList.
import java.util.*; public class MyClass { public static void main(String[] args) { //creating a ArrayList ArrayList<Integer> MyList = new ArrayList<Integer>(); ArrayList<Integer> arr = new ArrayList<Integer>(); //populating MyList MyList.add(10); MyList.add(20); MyList.add(30); //populating arr arr.add(100); arr.add(200); //printing ArrayList System.out.println("Before method call, MyList contains: " + MyList); MyList.addAll(1, arr); //printing ArrayList System.out.println("After method call, MyList contains: " + MyList); } }
The output of the above code will be:
Before method call, MyList contains: [10, 20, 30] After method call, MyList contains: [10, 100, 200, 20, 30]
❮ Java.util - ArrayList