The ArrayList.addall()
method in Java is used to add all the elements in a collection into a list.
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:
index
is an optional parameter. Ifindex
is not provided to theArrayList.addall()
method, the collectionc
elements are added at the end of the list.
The ArrayList.addall()
method returns true
if the elements from the collection c
are succesfully added to the list.
Note:
- If
index
is out of bound, theArrayList.addall()
method throws theIndexOutOfBoundsException
.- If the collection
c
isnull
, theArrayList.addall()
method throwsNullPointerException
.
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);}}
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
.