What is the ArrayList.addall() method in Java?
The ArrayList.addall() method in Java is used to add all the elements in a collection into a list.
Syntax
The ArrayList.addall() method can be declared as shown in the code snippet below:
public boolean addAll(int index, Collection c)
index: The index in the list where the first element from the collection is added.c: The collection from which the elements will be added to the list.
Note:
indexis an optional parameter. Ifindexis not provided to theArrayList.addall()method, the collectioncelements are added at the end of the list.
Return value
The ArrayList.addall() method returns true if the elements from the collection c are succesfully added to the list.
Note:
- If
indexis out of bound, theArrayList.addall()method throws theIndexOutOfBoundsException.- If the collection
cisnull, theArrayList.addall()method throwsNullPointerException.
Example
Consider the code snippet below, which demonstrates the use of the ArrayList.addall() method.
import java.io.*;import java.util.ArrayList;public class Example1 {public static void main(String args[]){ArrayList<String> list1 = new ArrayList<>(5);list1.add("Hello");list1.add("world");list1.add("!");System.out.println("list1:" + list1);ArrayList<String> list2 = new ArrayList<>(5);list2.add("This");list2.add("is");list2.add("addAll()");list2.add("example");System.out.println("list2:" + list2);list1.addAll(list2);System.out.println("list1:" + list1);}}
Explanation
Two lists, list1 and list2, are declared in line 7 and line 12 respectively. The ArrayList.addall() method is used in line 19 to add the elements in list2 to list1. As the parameter index is not passed to the ArrayList.addall() method, the elements are added at the end of list1.