Press "Enter" to skip to content

HashSet clear() Method in Java

The clear() method of HashSet removes all the elements from the HashSet. The HashSet becomes empty after the call to the clear() method.

Syntax

void clear()

Parameters

It does not take any parameter and does not return anything.
Freshers Placement

Return Value

It does not return anything.

Program 1

import java.util.HashSet;

public class HashSetClearExample {

	public static void main(String[] args) {

		HashSet<String> fruits = new HashSet<>();
		fruits.add("Apple");
		fruits.add("Banana");
		fruits.add("Grapes");
		fruits.add("Oranges");

		System.out.println("Set elements before clear: " + fruits);
		fruits.clear();
		System.out.println("Set elements after clear: " + fruits);
	}
}

Output

Set elements before clear: [Apple, Grapes, Oranges, Banana]
Set elements after clear: []

Program 2

import java.util.HashSet;

public class HashSetClearExample {

	public static void main(String[] args) {

		HashSet<Integer> set = new HashSet<>();
		set.add(10);
		set.add(20);
		set.add(30);
		set.add(40);
		set.add(50);

		System.out.println("Set elements before clear: " + set);
		set.clear();
		System.out.println("Set elements after clear: " + set);
	}
}

Output

Set elements before clear: [50, 20, 40, 10, 30]
Set elements after clear: []

Be First to Comment

Leave a Reply

Your email address will not be published.