What is the TreeSet.clear() function in Java?

The TreeSet.clear() method is part of the TreeSet class in the java.util package. TreeSet.clear() is used to remove all of the elements from a TreeSet.

The clear() method only removes the elements from the TreeSet; it does not delete the TreeSet itself.

Syntax

public void clear()

Parameters

The TreeSet.clear() method does not take any parameters.

Return value

TreeSet.clear() does not return anything, and simply clears the TreeSet upon which the method is called.

Example

Let’s understand with the help of an example.

We have a TreeSet:

  • [1, 8, 5, 3, 9]

When we use the TreeSet.clear() method on this TreeSet, it removes all the elements from the TreeSet, making the TreeSet empty.

So, the result of the TreeSet.clear() method is [ ].

Code

Let’s look at the code snippet below.

import java.io.*;
import java.util.TreeSet;
class Main
{
public static void main(String args[])
{
TreeSet<Integer> tree_set = new TreeSet<Integer>();
tree_set.add(1);
tree_set.add(8);
tree_set.add(5);
tree_set.add(3);
tree_set.add(0);
System.out.println("TreeSet: " + tree_set);
tree_set.clear();
System.out.println("TreeSet: " + tree_set);
}
}

Explanation

  • In lines 1 and 2, we import the required packages and classes.

  • In line 4, we create a Main class.

  • In line 6, we create a main function.

  • In line 8, we declare a TreeSet of Integer type.

  • In lines 9 to 13, we use the TreeSet.add() method to add the elements into the TreeSet.

  • In line 14, we display the original TreeSet.

  • In line 15, we use the TreeSet.clear() method to remove all the elements from the TreeSet.

  • In line 16, we display the result with a message.

Free Resources