Skip to Content

Remove all elements from Java LinkedHashSet example

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