1. Introduction

A HashSet in Java is part of the Java Collections Framework and is a set that uses a hash table for storage. It doesn’t allow duplicate elements. There might be cases where you want to remove all elements from the HashSet, leaving it empty. For this, you can use the clear() method provided by the HashSet class.

2. Program Steps

1. Create a HashSet and add some elements to it.

2. Print the HashSet to the console.

3. Clear the HashSet using the clear() method.

4. Print the HashSet again to confirm it is empty.

3. Code Program

import java.util.HashSet;

public class HashSetClear {

    public static void main(String[] args) {

        // Step 1: Create a HashSet and add some elements to it
        HashSet<String> fruits = new HashSet<>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Cherry");

        // Step 2: Print the HashSet to the console
        System.out.println("HashSet before clear: " + fruits);

        // Step 3: Clear the HashSet using the clear() method
        fruits.clear();

        // Step 4: Print the HashSet again to confirm it is empty
        System.out.println("HashSet after clear: " + fruits);
    }
}

Output:

HashSet before clear: [Banana, Cherry, Apple]
HashSet after clear: []

4. Step By Step Explanation

Step 1: A HashSet named fruits is created and some elements are added to it.

Step 2: The HashSet is printed to the console showing the elements it contains.

Step 3: The clear() method is called on the fruits HashSet, which removes all of the elements from this set.

Step 4: The HashSet is printed again, confirming that it is now empty, as indicated by the square brackets with no elements between them.