Java Utility Library

Java TreeSet - clear() Method



The java.util.TreeSet.clear() method is used to remove all of the elements from this set. The set will be empty after this call returns.

Syntax

public void clear()

Parameters

No parameter is required.

Return Value

void type.

Exception

NA

Example:

In the example below, the java.util.TreeSet.clear() method is used to clear all elements of the given set.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating treeset
    TreeSet<Integer> MySet = new TreeSet<Integer>();

    //populating the set
    MySet.add(10);
    MySet.add(20);
    MySet.add(30);
    MySet.add(40);

    //printing the set
    System.out.println("Before applying clear() method.");
    System.out.println("MySet contains: "+ MySet);

    MySet.clear();

    //printing the set
    System.out.println("\nAfter applying clear() method."); 
    System.out.println("MySet contains: "+ MySet);   
  }
}

The output of the above code will be:

Before applying clear() method.
MySet contains: [10, 20, 30, 40]

After applying clear() method.
MySet contains: []

❮ Java.util - TreeSet