Languages
[Edit]
EN

Java - clear HashSet

0 points
Created by:
Zachariah
298

In this article, we would like to show you how to clear the HashSet in Java.

Quick solution:

myHashSet.clear();

 

Practical example

In this example, we use clear() method to remove all items from the letters HashSet.

package hashsetOperations;

import java.util.*;

public class Example {

    public static void main(String[] args) {
        Set<String> letters = new HashSet<>();

        letters.add("A");
        letters.add("B");
        letters.add("C");

        System.out.println("Before: " + letters);  // [A, B, C]

        letters.clear();                           // removes all items

        System.out.println("After:  " + letters);  // []
    }
}

Output:

Before: [A, B, C]
After:  []
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Java Collections - HashSet

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join