Skip to Content

Remove all elements from Java TreeSet example

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