Java HashSet clear() Method Tutorial

In this section, we will learn what the HashSet clear() method is and how to use it in Java.

What is Java HashSet clear() Method?

The Java HashSet clear() method is used to remove the entire elements of a HashSet object and set its size to 0.

Java HashSet clear() Method Syntax:

public void clear()

clear() Method Parameters:

The method does not take an argument.

clear() Method Return Value:

The return value of this method is void.

clear() Method Exceptions:

The method does not throw an exception.

Example: using HashSet clear() method

import java.util.HashSet; 
public class Main {

    public static void main(String[] args){
      HashSet<Integer> set = new HashSet<>();
      set.add(1);
      set.add(2);
      set.add(3);
      set.add(4);
      set.add(5);
      set.add(6);
      set.add(7);

      System.out.println("The size of the set before calling the clear() method: "+set.size());
      set.clear();
      System.out.println("The size of the set after claing the clear() method: "+set.size());
    }
}

Output:

The size of the set before calling the clear() method: 7

The size of the set after claing the clear() method: 0
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies