Java TreeSet - addAll() Method
The java.util.TreeSet.addAll() method is used to add all of the elements in the specified collection to this set.
Syntax
public boolean addAll(Collection<? extends E> c)
Here, E is the type of element maintained by the container.
Parameters
c |
Specify the collection containing all elements which need to be added in the set. |
Return Value
Returns true if the TreeSet changed as a result of the call.
Exception
- Throws ClassCastException, if the elements provided cannot be compared with the elements currently in the set.
- Throws NullPointerException, if the specified collection is null or if any element is null and this set uses natural ordering, or its comparator does not permit null elements.
Example:
In the example below, the java.util.TreeSet.addAll() method is used to append all elements of the TreeSet Set2 at the end of TreeSet Set1.
import java.util.*; public class MyClass { public static void main(String[] args) { //creating a TreeSet TreeSet<Integer> Set1 = new TreeSet<Integer>(); TreeSet<Integer> Set2 = new TreeSet<Integer>(); //populating Set1 Set1.add(10); Set1.add(20); Set1.add(30); //populating Set2 Set2.add(100); Set2.add(200); //printing Set1 System.out.println("Before method call, Set1 contains: " + Set1); //appending all elements of Set2 into Set1 Set1.addAll(Set2); //printing TreeSet System.out.println("After method call, Set1 contains: " + Set1); } }
The output of the above code will be:
Before method call, Set1 contains: [10, 20, 30] After method call, Set1 contains: [10, 20, 30, 100, 200]
❮ Java.util - TreeSet