Java HashSet clear() Method Example

The clear() method of java.util.HashSet class will remove all the content of the HashSet

Signature

public void clear()

This method removes all of the elements from the HashSet.

Example

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

import java.util.HashSet;

public class ClearMethodHashSetExample 
{   
    public static void main(String args[])
    {
        // Create hashset1 object
        HashSet hashset1 = new HashSet();
                        
        //adding elements to HashSet using add()
        hashset1.add("Element1");
        hashset1.add("Element2");
        hashset1.add("Element3");
        hashset1.add("Element4");
        
        //Printing the elements of the HashSet1
        System.out.println("**Elements of the HashSet1 before clear**");
        System.out.println("Size of the hashset : "+hashset1.size());
        for(String val : hashset1)
        {
                System.out.println(val);
        }
        
        hashset1.clear();
        
        //Printing the elements of the HashSet1
        System.out.println("**Elements of the HashSet1 after clear**");
        System.out.println("Size of the hashset : "+hashset1.size());
        for(String val : hashset1)
        {
                System.out.println(val);
        }
    }
}

Output

**Elements of the HashSet1 before clear**
Size of the hashset : 4
Element1
Element2
Element3
Element4
**Elements of the HashSet1 after clear**
Size of the hashset : 0

Leave a Reply

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