Skip to Content

Remove all elements from Java HashSet example

  1. /*
  2.   Remove all elements from Java HashSet example
  3.   This Java Example shows how to remove all elements contained in Java HashSet
  4.   or clear HashSet object using clear or removeAll methods. It also shows how
  5.   to check whether HashSet object is empty or not using isEmpty method.
  6. */
  7.  
  8. import java.util.HashSet;
  9.  
  10. public class RemoveAllElementsFromHashSetExample {
  11.  
  12.   public static void main(String[] args) {
  13.  
  14.     //create object of HashSet
  15.     HashSet hSet = new HashSet();
  16.    
  17.     //add elements to HashSet object
  18.     hSet.add(new Integer("1"));
  19.     hSet.add(new Integer("2"));
  20.     hSet.add(new Integer("3"));
  21.    
  22.     System.out.println("HashSet before removal : " + hSet);
  23.    
  24.     /*
  25.       To remove all elements from Java HashSet or to clear HashSet object use,
  26.       void clear() method.
  27.       This method removes all elements from HashSet.
  28.     */
  29.    
  30.     hSet.clear();
  31.     System.out.println("HashSet after removal : " + hSet);
  32.    
  33.     /*
  34.       To check whether HashSet contains any elements or not use
  35.       boolean isEmpty() method.
  36.       This method returns true if the HashSet does not contains any elements
  37.       otherwise false.
  38.     */
  39.    
  40.     System.out.println("Is HashSet empty ? " + hSet.isEmpty());    
  41.    
  42.     /*
  43.       Please note that removeAll method of Java HashSet class can also be
  44.       used to remove all elements from HashSet object.
  45.     */
  46.   }
  47. }
  48.  
  49. /*
  50. Output would be
  51. HashSet before removal : [3, 2, 1]
  52. HashSet after removal : []
  53. Is HashSet empty ? true
  54. */