beginnersbook.com

  • Home
  • All Tutorials
    • Learn Servlet
    • Learn JSP
    • Learn JSTL
    • Learn C
    • Learn C++
    • Learn MongoDB
    • Learn XML
    • Learn Python
    • Learn Perl
    • Learn Kotlin
  • Core Java
  • OOPs
  • Collections
  • Java I/O
  • JSON
  • DBMS

Delete all the elements from HashSet

By Chaitanya Singh | Filed Under: Java.util package

Here we are gonna see how to remove all the elements of HashSet in one go. We can do so by calling clear() method of HashSet class.

Example

import java.util.HashSet;
class EmptyHashSetExample{ 
  public static void main(String[] args) {
     // Create a HashSet
     HashSet<String> hset = new HashSet<String>();
 
     //add elements to HashSet
     hset.add("Element1");
     hset.add("Element2");
     hset.add("Element3");
     hset.add("Element4");
     hset.add("Element5");
 
     // Display HashSet elements
     System.out.println("Before: HashSet contains: "+ hset);
 
     /* public void clear(): It removes all the elements
      * from HashSet. The set becomes empty after this
      * method gets called.
      */
     hset.clear();
 
     // Display HashSet content again
     System.out.println("After: HashSet contains: "+ hset);
  }
}

Output:

Before: HashSet contains: [Element1, Element2, Element3, Element4, Element5]
After: HashSet contains: []

Enjoyed this post? Try these related posts

  1. how to copy one hashmap content to another hashmap
  2. Difference between HashSet and TreeSet
  3. Iterate a LinkedList in reverse sequential order – java
  4. Convert HashSet to a List/ArrayList
  5. LinkedList push() and pop() methods – Java
  6. Difference between HashSet and HashMap

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Recently Added..

  • JSON Tutorial
  • Java Regular Expressions Tutorial
  • Java Enum Tutorial
  • Java Annotations Tutorial

Copyright © 2012 – 2021 BeginnersBook . Privacy Policy . Sitemap