HashSet clear() method in java

Let’s learn HashSet clear() method in java.

HashSet clear() method in java

clear() method of HashSet class removes all of the elements from this set.

The set will be empty after this call returns.

Syntax:

public void clear()

Parameter:

clear() method do not take any parameter.

Returns:

This method do not return any value.

Also read – HashSet in java

Now let’s see example on HashSet clear() method.

import java.util.HashSet;
public class HashSetClearMethodExample
{
   public static void main(String[] args)
   {
      HashSet<String> hs = new HashSet<String>();
      hs.add("Welcome");
      hs.add("hello");
      hs.add("world");
      hs.add("core");
      hs.add("java");
      System.out.println("HashSet before using clear() method: " + hs);
      // HashSet clear() method
      hs.clear();
      System.out.println("HashSet after using clear() method: " + hs);
   }
}


Output:

HashSet before using clear() method: [core, world, java, Welcome, hello]
HashSet after using clear() method: []


Reference – oracle docs