Java HashSet isEmpty() Method (original) (raw)

Last Updated : 23 Jan, 2025

The HashSet isEmpty() in Java is used to check if the HashSet is empty or not.

Syntax of HashSet isEmpty() Method

boolean isEmpty()

**Return Type: This method returns "true" if the HashSet is empty, otherwise returns "false".

**Example: This example demonstrates how the isEmpty() method **checks whether the given HashSet is empty or not.

Java `

// Java program to demonstrate the working of isEmpty() import java.util.HashSet;

public class Geeks { public static void main(String[] args) { // Create a new HashSet HashSet hs = new HashSet<>();

    System.out.println("HashSet: " + hs);
  
    // Check if the HashSet is empty
    System.out.println("Is the HashSet empty? "
                       + hs.isEmpty());

    // Add elements to the HashSet
    hs.add("Geek1");
    hs.add("Geek2");
    hs.add("Geek3");

    System.out.println("Updated HashSet: " + hs);
  
    // Check again if the HashSet is empty
    System.out.println("Is the HashSet empty? "
                       + hs.isEmpty());
}

}

`

Output

HashSet: [] Is the HashSet empty? true Updated HashSet: [Geek3, Geek2, Geek1] Is the HashSet empty? false