Home »
Java programming language
Java HashSet isEmpty() Method with Example
HashSet Class isEmpty() method: Here, we are going to learn about the isEmpty() method of HashSet Class with its syntax and example.
Submitted by Preeti Jain, on March 05, 2020
HashSet Class isEmpty() method
- isEmpty() method is available in java.util package.
- isEmpty() method is used to test whether this HashSet is empty (i.e. contains no elements) or not empty.
- isEmpty() method is a non-static method, it is accessible with the class object only, and if we try to access the method with the class name then we will get an error.
- isEmpty() method does not throw an exception at the time of checking the empty status of this HashSet.
Syntax:
public boolean isEmpty();
Parameter(s):
- It does not accept any parameter.
Return value:
The return type of the method is boolean, it returns true when this HashSet is empty otherwise it returns false.
Example:
// Java program to demonstrate the example
// of boolean isEmpty () method of HashSet
import java.util.*;
public class IsEmptyOfHashSet {
public static void main(String[] args) {
// Instantiates a HashSet object
HashSet < String > hs = new HashSet < String > ();
// By using add() method is to add
// the given object of this
// HashSet
hs.add("C");
hs.add("C++");
hs.add("JAVA");
hs.add("PHP");
hs.add("SFDC");
// Display HashSet
System.out.println("HashSet: " + hs);
// By using isEmpty() method is
// to check whether this HashSet is
// empty or not
boolean status = hs.isEmpty();
// Display status
System.out.println("hs.isEmpty(): " + status);
}
}
Output
HashSet: [JAVA, C++, C, SFDC, PHP]
hs.isEmpty(): false