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
Call
What 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>
Half-open range view.subSet(20, 50) covers 20, 35, and 45, stopping before 50.
Targeted wipe. Calling clear() on that view removes only those three prices from the original prices tree.
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.