Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator

What is the HashSet.clear() method in Java?

Harsh Jain

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

The HashSet.clear() method is present in the HashSet class inside the java.util package. It clears all the elements from the HashSet, i.e., it empties the existing HashSet but does not delete the HashSet.

Let’s understand this with the help of an example. Suppose that a HashSet contains [1, 8, 5, 3 , 0]. Upon using the hashSet.clear() method, the HashSet becomes empty and when we display the elements of the HashSet, we get an empty array ([ ]).

Parameter

The HashSet.clear() doesn’t accept any parameters.

Return value

The HashSet.clear() doesn’t return any value.

Code

Let’s have a look at the code:

import java.io.*;
import java.util.HashSet;
class Main
{
public static void main(String args[])
{
HashSet<Integer> hash_set1 = new HashSet<Integer>();
hash_set1.add(1);
hash_set1.add(8);
hash_set1.add(5);
hash_set1.add(3);
hash_set1.add(17);
hash_set1.clear();
System.out.println("hash_set1 after using HashSet.clear(): "
+ hash_set1);
}
}
Using the hashset.clear() function in Java

Explanation

  • In lines 1 and 2, we import the required packages and classes.

  • In line 4, we make the Main class.

  • In line 6, we make the main() function.

  • In line 8, we declare a HashSet of the integer type i.e., hash_set1.

  • From lines 9 to 13, we add the elements into the HashSet by using the HashSet.add() method.

  • In line 14, we use the HashSet.clear() method to empty the Hashset.

  • In line 16, we display the HashSet after using the HashSet.clear() method with a message.

RELATED TAGS

java
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring