Java TreeSet clear() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
TreeSet

Definition

In Java, clear() deletes every element from the TreeSet, leaving size() at 0 and isEmpty() as true. It returns nothing (void).

Clearing a set resets only its contents: any custom Comparator attached to the TreeSet remains active for future additions. On a range view like subSet(), clear() deletes only the view's slice from the backing set.

An instance method of java.util.TreeSet (Java 1.2+): a red-black tree NavigableSet backed by a TreeMap that keeps unique elements sorted in O(log n) time and is not thread-safe.

Syntax

Call clear() with no arguments to empty a set or a range slice.

Java
TreeSet<String> sessions = new TreeSet<>(Arrays.asList("s1", "s2", "s3"));
sessions.clear();                 // []
sessions.subSet("a", "m").clear(); // removes only [a..m) from the set
CallWhat it does
set.clear()Removes all elements; size becomes 0.
set.headSet(x).clear()Removes every element below x from the original set.
set.subSet(a, b).clear()Deletes a bounded slice in one call.
set.isEmpty()Returns true after clearing.

If active iterators exist when clear() runs on a non-empty set, their next step throws ConcurrentModificationException.

Library declarations
Java
// java.util.TreeSet<E>
public void clear()

// Declared in Set<E> and Collection<E>

Parameters

ParameterDescription
Noneclear() takes no parameters.

Return Value

Return ValueDescription
voidNothing is returned; the set is now empty.

Compare with Similar Methods

Ways to empty or shrink a TreeSet:

MethodHow it differs
remove(o)Removes a single specified element.
subSet(a, b).clear()Clears only elements inside a specific range.
pollFirst()Pops elements one by one while reading them.
set = new TreeSet<>()Replaces only the local variable; other references keep the old data.

Java Examples

Example 1 — Reset Active Sessions and Reuse the Set

Clear active session IDs at midnight, verify the set is empty, and add fresh IDs for the new day.

Java
import java.util.Arrays;
import java.util.TreeSet;

public class TreeSetClearSessions {
    public static void main(String[] args) {
        TreeSet<String> active = new TreeSet<>(Arrays.asList("u104", "u101", "u109"));
        System.out.println("before clear: " + active + " size=" + active.size());

        active.clear();
        System.out.println("after clear:  " + active + " empty? " + active.isEmpty());

        active.clear();
        active.add("u201");
        System.out.println("reused set:   " + active);
    }
}

How It Works

  1. Emptied in one call. active.clear() drops all three IDs, bringing size() to 0 and isEmpty() to true.
  2. Safe on an empty set. Calling clear() a second time does nothing and throws no exception.
  3. Ready for reuse. The cleared TreeSet immediately accepts "u201" without allocating a new object.

Example 2 — clear() Keeps the Custom Comparator

Empty a descending TreeSet, add new numbers, and confirm it still sorts largest to smallest.

Java
import java.util.Arrays;
import java.util.Comparator;
import java.util.TreeSet;

public class TreeSetClearComparator {
    public static void main(String[] args) {
        TreeSet<Integer> leaderboard = new TreeSet<>(Comparator.reverseOrder());
        leaderboard.addAll(Arrays.asList(10, 50, 30));
        System.out.println("round 1: " + leaderboard);

        leaderboard.clear();
        System.out.println("comparator still set? " + (leaderboard.comparator() != null));

        leaderboard.addAll(Arrays.asList(12, 85, 44));
        System.out.println("round 2: " + leaderboard);
    }
}

How It Works

  1. Sorting rule lives on the set. Clearing the nodes does not reset the comparator passed to the constructor.
  2. Verified non-null. leaderboard.comparator() still returns the reverse comparator after clear().
  3. Next round stays descending. Adding 12, 85, and 44 produces [85, 44, 12] automatically.

Example 3 — Use clear() on a subSet View to Delete a Range

Delete middle prices between 20 and 50 from a sorted catalog while keeping items outside that range.

Java
import java.util.Arrays;
import java.util.TreeSet;

public class TreeSetClearSlice {
    public static void main(String[] args) {
        TreeSet<Integer> prices = new TreeSet<>(Arrays.asList(10, 20, 35, 45, 50, 75));
        System.out.println("catalog: " + prices);

        prices.subSet(20, 50).clear();
        System.out.println("after clearing [20, 50): " + prices);
    }
}

How It Works

  1. Half-open range view. subSet(20, 50) covers 20, 35, and 45, stopping before 50.
  2. Targeted wipe. Calling clear() on that view removes only those three prices from the original prices tree.
  3. Boundary items untouched. 10 (below 20) and 50, 75 (at or above 50) stay in the catalog.

Frequently Asked Questions

It removes all elements from the TreeSet, making size() equal to 0 and isEmpty() true.
No. The comparator stays attached to the set, so new elements added afterward are sorted by the same rule.
Nothing happens and no error is thrown; the set simply stays empty.
clear() empties the existing object so all references see an empty set and the comparator stays. Assigning new TreeSet<>() creates a fresh object and only updates one variable.
Yes. Slice a view with subSet(), headSet(), or tailSet() and call clear() on that view to remove just those elements.

Next: clone()

Create a shallow copy of the TreeSet with the same comparator.

clone() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

10 people found this page helpful