The addAll() method of the java.util.Collections class is used to add multiple elements to a collection at once. It is faster than repeatedly calling add() and is a convenient way to insert elements individually or from an array. It throws NullPointerException if the collection or elements are null, or if the collection does not allow null values.
Example:
import java.util.*;
public class GFG {
public static void main(String[] args) {
List<String> list = new ArrayList<>(Arrays.asList("A", "B", "C"));
Collections.addAll(list, "D", "E", "F");
System.out.println("Updated List: " + list);
}
}
Output
Updated List: [A, B, C, D, E, F]
Explanation:
- Collections.addAll() adds multiple elements to a collection in one call.
- Works with any collection like ArrayList or HashSet.
- Saves time compared to adding elements one by one.
Syntax
public static <T> boolean addAll(Collection<T> c, T... elements)
Parameters:
- c : The collection to which elements are to be added.
- elements : Elements to add to the collection.
Return Value: Returns true if the collection changed as a result of the call.
Example 1: This code shows how to use Collections.addAll() to efficiently add multiple elements to a Java List at once.
import java.util.*;
public class GFG {
public static void main(String[] args) {
List<String> list = new ArrayList<>(Arrays.asList("A", "B", "C", "Tajmahal"));
System.out.println("list before operation: " + list);
boolean result = Collections.addAll(list, "1", "2", "3");
System.out.println("Result of addAll: " + result);
System.out.println("list after operation: " + list);
}
}
Output
list before operation: [A, B, C, Tajmahal] Result of addAll: true list after operation: [A, B, C, Tajmahal, 1, 2, 3]
Explanation:
- An ArrayList is created with initial elements "A", "B", "C", "Tajmahal".
- Collections.addAll() adds "1", "2", "3" to the list in a single call.
- The method returns true if the list is modified.
Example 2: This code demonstrates that Collections.addAll() throws a NullPointerException if the target collection is null, showing proper exception handling.
import java.util.*;
public class GFG {
public static void main(String[] args) {
List<String> list = new ArrayList<>(Arrays.asList("A", "B", "C", "Tajmahal"));
System.out.println("list before operation: " + list);
try {
Collections.addAll(null, list.toArray(new String[0]));
} catch (NullPointerException e) {
System.out.println("Exception thrown: " + e);
}
}
}
Output
list before operation: [A, B, C, Tajmahal] Exception thrown: java.lang.NullPointerException: Cannot invoke "java.util.Collection.add(Object)" because "c" is null
Explanation :
- The program attempts to add these elements to a null collection using Collections.addAll().
- Since the target collection is null, a NullPointerException is thrown.
- The exception is caught in the catch block and printed