What is the TreeSet.isEmpty() function in Java?
The TreeSet.isEmpty() method is present in the TreeSet class in the java.util package.
It is used to check whether a TreeSet is empty or contains any elements in it.
Parameter
The TreeSet.isEmpty() method doesn’t take any parameters.
Return value
The method returns a Boolean value.
True: When theTreeSetis empty.False: When theTreeSetis not empty.
Examples
Example 1
TreeSet = [1,8,5,3,9]
It contains some elements, i.e., the TreeSet is not empty.
So, the result of the TreeSet.isEmpty() method is false.
Example 2
TreeSet = [ ]
This one doesn’t contain any elements, i.e., the TreeSet is empty.
So, the result of the TreeSet.isEmpty() method is true.
Code
Let us look at the code snippet below.
import java.io.*;import java.util.TreeSet;class Main{public static void main(String args[]){TreeSet<Integer> tree_set = new TreeSet<Integer>();tree_set.add(1);tree_set.add(8);tree_set.add(5);tree_set.add(3);tree_set.add(0);System.out.println("TreeSet is empty? : " + tree_set.isEmpty());tree_set.clear();System.out.println("TreeSet is empty? : " + tree_set.isEmpty());}}
Explanation
-
In lines 1 and 2, we import the required packages and classes.
-
In line 4, we made a
Mainclass. -
In line 6, we made a
mainfunction. -
In line 8, we declared a
TreeSetofIntegertype. -
In lines 9 to 13, we add the elements into the
TreeSetby using theTreeSet.add()method. -
In lines 14 and 17, we display the result of whether the
TreeSetis empty or not usingTreeSet.isEmpty()method with a message. -
In line 16, we removed all the elements from the
TreeSetby usingTreeSet.clear()method.
In this way, the TreeSet.isEmpty() method can be used to check whether the TreeSet is empty or not.