In Java, clone() creates and returns a new TreeSet holding the same elements and the same Comparator as the original set.
It makes a shallow copy: adding or removing elements in the clone never changes the original set, yet mutable objects inside both sets are shared. Also, clone() returns Object and is declared on TreeSet, not on the Set or NavigableSet interfaces.
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 clone() on a variable typed as TreeSet and cast the result.
Java
TreeSet<Integer> original = new TreeSet<>(Arrays.asList(10, 20, 30));
@SuppressWarnings("unchecked")
TreeSet<Integer> copy = (TreeSet<Integer>) original.clone();
Call
What it does
(TreeSet<T>) set.clone()
Shallow copy keeping the original's comparator; requires a cast.
new TreeSet<>((SortedSet<T>) set)
Copy constructor keeping the comparator with no cast.
new TreeSet<>((Collection<T>) set)
Copies elements using natural order (drops comparator!).
copy.add(x)
Modifies only the copy's tree structure.
If your variable is typed as Set<T> or NavigableSet<T>, clone() will not compile; either use TreeSet<T> or pass the SortedSet to new TreeSet<>(set).
Library declarations
Java
// java.util.TreeSet<E>
public Object clone()
// TreeSet implements Cloneable
Parameters
Parameter
Description
None
clone() takes no parameters.
Return Value
Return Value
Description
Object
A shallow copy of this TreeSet; cast it to TreeSet<E>.
Compare with Similar Methods
Ways to duplicate a sorted set:
Method
How it differs
new TreeSet<>(sortedSet)
Keeps the comparator, avoids casts and unchecked warnings.
Clone keeps custom order. Both cloned and viaSorted preserve reverseOrder() and keep [3, 2, 1].
Overload choice matters. When the variable has static type Collection, Java picks TreeSet(Collection) instead of TreeSet(SortedSet).
Natural order fallback.viaColl ignores the source comparator and re-sorts elements into [1, 2, 3] with a null comparator.
Frequently Asked Questions
Shallow. The clone gets its own internal red-black tree, but the element objects stored inside both sets are the same references.
It overrides Object.clone(), so callers must cast the result back to a typed TreeSet. Add @SuppressWarnings("unchecked") or use new TreeSet<>(sortedSet) instead.
Yes. The cloned TreeSet uses the exact same Comparator (or natural ordering) as the original.
Because Set and NavigableSet do not declare public clone(). Declare the variable as TreeSet or use new TreeSet<>(sortedSet).
TreeSet(SortedSet) copies the comparator and builds quickly in sorted order; TreeSet(Collection) always uses natural ordering.