Java HashSet isEmpty() Method Example

The isEmpty() method of java.util.HashSet class will tests if the HashSet has any elements or not.

Signature

public boolean isEmpty() 

This method checks if the hashset has any elements in it or not, returns true if and only if the hashset has no components,else it will return false.

Example

The following example shows the usage of java.util.HashSet.isEmpty() method.

import java.util.HashSet;

public class IsEmptyMethodHashSetExample 
{
    public static void main(String args[])
    {
     // create an empty HashSet
        HashSet hashSet1 = new HashSet();
        
        // use add() method to add elements to the HashSet
        hashSet1.add("Element1");
        hashSet1.add("Element2");
        hashSet1.add("Element3");
        
        //Check if hashSet1 is empty or not 
        System.out.println("Is \"hashSet1\" empty : "+hashSet1.isEmpty());
    }
}

Output

Is "hashSet1" empty : false

Leave a Reply

Your email address will not be published. Required fields are marked *