HashSet Clear trong java với ví dụ cụ thể

Để xoá tất cả các phần tử trong HashSet chúng ta có clear() method được dựng sẵn trong HashSet class.

Ví dụ

import java.util.HashSet;
public class Main {
    public static void main(String[] args) {
        // Create a HashSet
        HashSet<String> hset = new HashSet<String>();

        //add elements to HashSet
        hset.add("h1");
        hset.add("h2");
        hset.add("h3");
        hset.add("h4");
        hset.add("h5");

        // Display HashSet elements
        System.out.println("Before: HashSet contains: "+ hset);

        hset.clear();

        // Display HashSet content again
        System.out.println("After: HashSet contains: "+ hset);
    }
}

Output:

Before: HashSet contains: [h1, h2, h3, h4, h5]
After: HashSet contains: []

 

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x