What is the HashSet.isEmpty() function in Java?
The HashSet.isEmpty() method is present in the HashSet class inside the java.util package.
It is used to check whether a HashSet contains any elements in it or not.
Let’s understand with the help of some examples:
-
Suppose a
HashSetcontains[1, 8, 5, 3, 0]. It contains some elements, i.e., theHashSetis not empty. So, the result of theHashSet.isEmpty()method isfalse. -
Now, suppose a
HashSetcontains[ ]. It doesn’t contain any elements, i.e., theHashSetis empty. So, the result of theHashSet.isEmpty()method here istrue.
Parameters
The HashSet.isEmpty() method does not accept any parameters.
Return value
The HashSet.isEmpty() method returns a Boolean value where true denotes that the HashSet is empty and false denotes that the HashSet is not empty.
Code
Let’s have a look at the code:
import java.util.HashSet;class Main{public static void main(String args[]){HashSet<Integer> hash_set = new HashSet<Integer>();hash_set.add(1);hash_set.add(8);hash_set.add(5);hash_set.add(3);hash_set.add(0);System.out.println("HashSet is empty? : " +hash_set.isEmpty());hash_set.clear();System.out.println("HashSet is empty? : " +hash_set.isEmpty());}}
Explanation
- In lines 1 and 2, we imported the required packages and classes.
- In line 4, we defined the
Mainclass. - In line 6, we created the
main()function. - In line 8, we declared the
HashSetas Integer type. - In lines 10 to 14, we add the elements into the
HashSetby using theHashSet.add()method. - In line 15, we displayed the result, that is whether the
HashSetis empty or not using theHashSet.isEmpty()method with a message. - In line 17, we removed all the elements from the
HashSetby using theHashSet.clear()method. - In line 19, we displayed the result using the
HashSet.isEmpty()method with a message.