Skip to content

Java TreeSet Clear – Remove All Elements Example

This example shows how to clear TreeSet in Java. This example also shows how to remove all elements from TreeSet using the clear and removeAll methods.

How to clear or remove all elements from TreeSet in Java?

There are various ways using which we can clear the TreeSet or remove all elements from it.

1. Using the clear method

The clear method of the TreeSet class removes all the elements from the set object.

The TreeSet will be empty after this method call.

Output

Please also visit how to check if the TreeSet is empty example to know more.

2. Using the removeAll method

The removeAll method of the TreeSet class removes all elements from this set that are also present in the specified collection object.

To clear the TreeSet, we will pass the same TreeSet object to make it empty.

Output

3. By assigning a new object

We can also assign a new TreeSet object to the same reference to make it empty as given below.

Output

Which method should I use to remove all TreeSet elements?

The clear and removeAll methods iterate the TreeSet object and remove the elements one by one. Both of the methods make the elements eligible for the garbage collection if they are not being referenced from anywhere else.

Both of these methods also do not change the capacity of the internal NavigableMap object. As compared to removeAll, the clear method is more readable so it should be preferred over the removeAll method.

When we assign a new object to the same reference, all elements of the TreeSet plus the original TreeSet object become eligible for the garbage collection if not referenced from anywhere else. Additionally, a new object needs to be created which is a costly operation in terms of performance. It also resets the capacity of the internal map object to the default capacity.

If you are going to add roughly the same number of elements to TreeSet after clearing it, the clear method is the suggested approach to avoid frequent capacity allocations. If not, we can assign a new object to the same reference.

This example is a part of the Java TreeSet Tutorial with Examples.

Please let me know your views in the comments section below.

References:
Java 8 TreeSet

About the author

Leave a Reply

Your email address will not be published.