Java Utility Library

Java HashSet - clear() Method



The java.util.HashSet.clear() method is used to clear all elements of the set. This method makes the set empty with a size of zero.

Syntax

public void clear()

Parameters

No parameter is required.

Return Value

void type.

Exception

NA

Example:

In the example below, the java.util.HashSet.clear() method is used to clear all elements of the given set.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a hash set
    HashSet<Integer> MySet = new HashSet<Integer>();

    //populating the set
    MySet.add(10);
    MySet.add(20);
    MySet.add(30);
    MySet.add(40);

    //printing the set
    System.out.println("Before applying clear() method.");
    System.out.println("MySet contains: "+ MySet);

    //clearing all elements
    MySet.clear();

    //printing the set again
    System.out.println("\nAfter applying clear() method."); 
    System.out.println("MySet contains: "+ MySet);   
  }
}

The output of the above code will be:

Before applying clear() method.
MySet contains: [20, 40, 10, 30]

After applying clear() method.
MySet contains: []

❮ Java.util - HashSet