In this section, we will learn what the TreeSet add() and addAll() methods are and how to use them in Java.
What is Java TreeSet add() Method?
The Java TreeSet add() method is used to add an element to a TreeSet object.
Java add() Method Syntax:
public boolean add(E e)
add() Method Parameters:
The method takes one argument and that is the element we want to add to the target TreeSet object.
add() Method Return Value:
The return value of this method is of type Boolean.
If the value we’ve set as the argument of this method didn’t exist in the list and calling this method caused a new element to be added, then the return value of this method becomes true.
Otherwise, the value false will return instead.
add() Method Exceptions:
The method might throw two types of exceptions:
ClassCastException: We get this exception if the argument is of incompatible type compared to the elements in the target TreeSet object.
NullPointerException: we get this exception if the argument is a null value.
Example: using TreeSet add() method
import java.util.TreeSet; class Main{ public static void main(String[] args) { TreeSet<Integer> ts = new TreeSet<>(); ts.add(200); ts.add(2); ts.add(3); ts.add(0); ts.add(10); ts.add(30); System.out.println(ts.last()); } }
Output:
200
What is Java TreeSet addAll() Method?
The Java TreeSet addAll() method is used to add the elements of another collection to a TreeSet object.
Basically, when we want to add multiple elements at one call to a TreeSet object, we use this method.
Java addAll() Method Syntax:
public boolean addAll(Collection<? extends E> c)
addAll() Method Parameters:
The method takes one argument and that is a reference to the collection object we want to copy its elements and put them as the elements of a TreeSet object.
addAll() Method Return Value:
The return value of this method is of type boolean.
If one or more elements were passed to the target TreeSet object (Basically, if the target TreeSet object was changed as a result of calling this method) then the return value will be true.
Otherwise, if nothing happened (perhaps because the elements of the reference collection are already existing in the target TreeSet object) then the return value of this method becomes false because nothing changed as a result of calling the method.
addAll() Method Exceptions:
ClassCastException: We get this exception if the argument is of incompatible type compared to the elements in the target TreeSet object.
NullPointerException: We get this exception if the argument is a null value.
Example: using TreeSet addAll() method
import java.util.TreeSet; import java.util.ArrayList; class Main{ public static void main(String[] args) { TreeSet<Integer> ts = new TreeSet<>(); ts.add(200); ts.add(2); ts.add(3); ts.add(0); ts.add(10); ts.add(30); ArrayList<Integer> list = new ArrayList<>(); list.add(1000); list.add(2000); list.add(3000); ts.addAll(list); for (int i: ts){ System.out.println(i); } } }
Output:
0 2 3 10 30 200 1000 2000 3000