Remove all elements from HashSet in Java

In this tutorial, we will learn about how to Remove all elements from HashSet in Java.

HashSet in Java extends AbstractSet and implements Set interface which is backed by hash table.  It creates a collection that uses a hash table for storage. This class makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. This class permits null element. HashSet does not guarantee the order of its elements, because the process of hashing doesn’t usually lend itself to the creation of sorted sets.

If we want to delete/remove all the elements from HashSet, then this class provides clear() method to remove all elements from HashSetThe syntax of clear() method is:

Syntax of clear() method:

this method removes all the elements from this list. The list will be empty after this call returns.

Example:

Output:

In the above program, we have used clear() method to remove all the elements from HashSet.

Related posts

Leave a Comment