How to Remove All Elements of a HashSet in Java


In this example we will show how to remove all elements of a HashSet in Java.

Source Code

package com.beginner.examples;

import java.util.HashSet;

public class ClearHashSet {

  public static void main(String[] args) {
    // Create a HashSet object
    HashSet sets = new HashSet();
    sets.add("A");
    sets.add("B");

    sets.clear(); // remove all elements of a HashSet
    System.out.println(sets);
  }
}

Output:

[]

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments