AbstractCollection addAll() Method in Java
Last Updated :
12 Feb, 2025
Improve
The addAll() method of Java AbstractCollection is used to append all elements from a given collection to the current collection. If the collection being appended is a TreeSet, the elements are stored in sorted order, as TreeSet maintains a natural ordering. It is important to note that AbstractCollection cannot be instantiated directly, so we use Collection as the type instead.
Example 1: Adding Elements from One Collection to Another
In this example, we append all the elements from one collection to another using the addAll() method.
import java.util.*;
public class Geeks {
public static void main(String args[]) {
// Creating an empty collection
// (TreeSet maintains elements in sorted order)
Collection<String> c1 = new TreeSet<>();
// Adding elements to the collection
c1.add("Welcome");
c1.add("To");
c1.add("Geeks");
c1.add("4");
c1.add("Geeks"); // Duplicate, will be removed
c1.add("TreeSet");
System.out.println("Collection 1: " + c1);
// Creating another empty Collection
Collection<String> c2 = new TreeSet<>();
// Displaying the empty Collection
System.out.println("Collection 2 (before addAll): " + c2);
// Using addAll() method to append elements
c2.addAll(c1);
// Displaying the Collection after adding elements
System.out.println("Collection 2 (after addAll): " + c2);
}
}
Output
Collection 1: [4, Geeks, To, TreeSet, Welcome] Collection 2 (before addAll): [] Collection 2 (after addAll): [4, Geeks, To, TreeSet, Welcome]
Syntax of AbstractCollection addAll()
boolean addAll(Collection c);
- Parameters: The parameter “c” is a collection of any type that is to be added to the collection.
- Return Value: The method returns “true” if it successfully appends the elements of collection c to the existing collection otherwise, it returns “false”.
- Exceptions:
- NullPointerException: If the specified collection is null.
- UnsupportedOperationException: If the collection does not support the add() operation.
Example 2: Using addAll() method with integer value
import java.util.*;
public class Geeks {
public static void main(String args[]) {
// Creating an empty collection
Collection<Integer> c1 = new TreeSet<>();
// Adding elements into the Collection
c1.add(10);
c1.add(20);
c1.add(30);
c1.add(40);
c1.add(50);
// Displaying the Collection
System.out.println("Collection 1: " + c1);
// Creating another empty Collection
Collection<Integer> c2 = new TreeSet<>();
// Displaying the empty Collection
System.out.println("Collection 2 (before addAll): " + c2);
// Using addAll() method to append elements
c2.addAll(c1);
// Displaying the Collection after adding elements
System.out.println("Collection 2 (after addAll): " + c2);
}
}
Output
Collection 1: [10, 20, 30, 40, 50] Collection 2 (before addAll): [] Collection 2 (after addAll): [10, 20, 30, 40, 50]