Java HashSet - isEmpty() Method
The java.util.HashSet.isEmpty() method is used to check whether the set is empty or not. It returns true if the set contains no elements, else returns false.
Syntax
public boolean isEmpty()
Parameters
No parameter is required.
Return Value
Returns true if the set contains no elements, else returns false.
Exception
NA
Example:
In the example below, the java.util.HashSet.isEmpty() method is used to check whether the given set contains any element or not.
import java.util.*; public class MyClass { public static void main(String[] args) { //creating hash set HashSet<Integer> MySet = new HashSet<Integer>(); //checking for empty System.out.println("Is MySet empty?: "+ MySet.isEmpty()); //populating hash set MySet.add(10); MySet.add(20); MySet.add(30); MySet.add(40); //checking for empty System.out.println("Is MySet empty?: "+ MySet.isEmpty()); } }
The output of the above code will be:
Is MySet empty?: true Is MySet empty?: false
❮ Java.util - HashSet