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
    • Learn jQuery
  • 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: []

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 – 2022 BeginnersBook . Privacy Policy . Sitemap