The addAll() method adds all the elements of a collection to the arraylist.
Example
Syntax of ArrayList addAll()
The syntax of the addAll() method is:
arraylist.addAll(int index, Collection c)
Here, arraylist is an object of the ArrayList class.
addAll() Parameters
The ArrayList addAll() method can take two parameters:
- index (optional) - index at which all elements of a collection is inserted
- collection - collection that contains elements to be inserted
If the index parameter is not passed the collection is appended at the end of the arraylist.
addAll() Return Value
- returns
trueif the collection is successfully inserted into the arraylist - raises
NullPointerExceptionif the specified collection is null - raises
IndexOutOfBoundsExceptionif theindexis out of range
Example 1: Inserting Elements using ArrayList addAll()
Output
Prime Numbers: [3, 5] Numbers: [1, 2, 3, 5]
In the above example, we have created two arraylists named primeNumbers and numbers. Notice the line,
numbers.addAll(primeNumbers);
Here, the addAll() method does not contain the optional index parameter. Hence, all elements from the arraylist primeNumbers are added at the end of the arraylist numbers.
Note: We have used the add() method to add single elements to arraylist. To learn more, visit Java ArrayList add().
Example 2: Inserting Elements to the Specified Position
Output
ArrayList 1: [Java, Python] ArrayList 2: [JavaScript, C] Updated ArrayList 2: [JavaScript, Java, Python, C]
In the above example, we have two arraylists named languages1 and languages2. Notice the line,
languages2.addAll(1, languages1);
Here, the addAll() contains the optional index parameter. Hence, all elements from the arraylist languages1 are added to languages at index 0.
Example 3: Inserting Elements from Set to ArrayList
Output
Set: [Java, JavaScript, Python] Initial ArrayList: [English] Updated ArrayList: [English, Java, JavaScript, Python]
In the above example, we have created a hashset named set and an arraylist named list. Notice the line,
list.addAll(set);
Here, we have used the addAll() method to add all the elements of the hashset to the arraylist. The optional index parameter is not present in the method. Hence, all elements are added at the end of the arraylist.