TreeSet clear() method in java

Let’s learn TreeSet clear() method in java.

TreeSet clear() method in java

clear() method of TreeSet class removes all of the elements from this set.

The set will be empty after this call returns.

Syntax:

public void clear()

Parameters:

clear() method do not take parameter.

Also read – TreeSet in java

Now let’s see example on TreeSet clear() method.

import java.util.TreeSet;
public class TreeSetClearMethodExample
{
   public static void main(String[] args)
   {
      TreeSet<String> ts = new TreeSet<String>();
      ts.add("grapes");
      ts.add("apple");
      ts.add("mango");
      ts.add("banana");
      ts.add("orange");
      ts.add("pineapple");
      System.out.println("TreeSet before using clear() method: " + ts);
      // clear TreeSet using clear() method
      ts.clear();
      // print final TreeSet
      System.out.println("TreeSet after using clear() method: " + ts);
   }
}


Output:

TreeSet before using clear() method: [apple, banana, grapes, mango, orange, pineapple]
TreeSet after using clear() method: []