EN
Java - clear HashSet
0 points
In this article, we would like to show you how to clear the HashSet in Java.
Quick solution:
xxxxxxxxxx
1
myHashSet.clear();
In this example, we use clear()
method to remove all items from the letters
HashSet.
xxxxxxxxxx
1
package hashsetOperations;
2
3
import java.util.*;
4
5
public class Example {
6
7
public static void main(String[] args) {
8
Set<String> letters = new HashSet<>();
9
10
letters.add("A");
11
letters.add("B");
12
letters.add("C");
13
14
System.out.println("Before: " + letters); // [A, B, C]
15
16
letters.clear(); // removes all items
17
18
System.out.println("After: " + letters); // []
19
}
20
}
Output:
xxxxxxxxxx
1
Before: [A, B, C]
2
After: []