Java TreeSet clone() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
TreeSet

Definition

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();
CallWhat 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

ParameterDescription
Noneclone() takes no parameters.

Return Value

Return ValueDescription
ObjectA shallow copy of this TreeSet; cast it to TreeSet<E>.

Compare with Similar Methods

Ways to duplicate a sorted set:

MethodHow it differs
new TreeSet<>(sortedSet)Keeps the comparator, avoids casts and unchecked warnings.
toArray()Copies sorted elements into an array instead of a set.
descendingSet()Live reversed view (shares changes), not an independent copy.
ArrayList.clone()Same shallow-copy pattern for a resizable list.

Java Examples

Example 1 — Clone Exam IDs and Verify Structural Independence

Make a clone of sorted exam IDs, mutate the copy, and verify the original remains untouched.

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

public class TreeSetCloneIds {
    @SuppressWarnings("unchecked")
    public static void main(String[] args) {
        TreeSet<Integer> original = new TreeSet<>(Arrays.asList(201, 105, 310));
        TreeSet<Integer> backup = (TreeSet<Integer>) original.clone();

        backup.add(405);
        backup.remove(105);

        System.out.println("original: " + original);
        System.out.println("backup:   " + backup);
        System.out.println("same instance? " + (original == backup));
    }
}

How It Works

  1. Cast with warning suppression. Because clone() returns Object, casting to TreeSet<Integer> requires @SuppressWarnings("unchecked") for clean builds.
  2. Separate trees. Adding 405 and removing 105 on backup leaves original unchanged at [105, 201, 310].
  3. Distinct objects. original == backup evaluates to false because two separate TreeSet wrappers and trees exist.

Example 2 — Shallow Copy: Mutable Objects Are Shared Across Both Sets

Clone a set of tasks sorted by ID, update a task's status field, and observe both sets seeing it.

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

public class TreeSetCloneShallow {
    static class Task {
        final int id;
        String status;
        Task(int id, String status) { this.id = id; this.status = status; }
        public String toString() { return id + ":" + status; }
    }

    @SuppressWarnings("unchecked")
    public static void main(String[] args) {
        TreeSet<Task> tasks = new TreeSet<>(Comparator.comparingInt(t -> t.id));
        Task first = new Task(1, "open");
        tasks.add(first);
        tasks.add(new Task(2, "open"));

        TreeSet<Task> copy = (TreeSet<Task>) tasks.clone();
        first.status = "done";

        System.out.println("original: " + tasks);
        System.out.println("copy:     " + copy);
        System.out.println("same Task object? " + (tasks.first() == copy.first()));
    }
}

How It Works

  1. Comparator uses immutable ID. Comparing by t.id keeps tree sorting stable even when t.status changes.
  2. Shared object references. clone() copies references to the same Task instances rather than constructing new ones.
  3. Mutation visible everywhere. Setting first.status = "done" updates both tasks and copy because tasks.first() == copy.first().

Example 3 — clone() and TreeSet(SortedSet) Keep the Comparator; Collection Does Not

Compare clone() with the SortedSet copy constructor and the Collection copy constructor.

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

public class TreeSetCloneVsCopy {
    @SuppressWarnings("unchecked")
    public static void main(String[] args) {
        TreeSet<Integer> desc = new TreeSet<>(Comparator.reverseOrder());
        desc.addAll(Arrays.asList(1, 3, 2));

        TreeSet<Integer> cloned = (TreeSet<Integer>) desc.clone();
        TreeSet<Integer> viaSorted = new TreeSet<>(desc);
        Collection<Integer> asColl = desc;
        TreeSet<Integer> viaColl = new TreeSet<>(asColl);

        System.out.println("cloned:    " + cloned + " cmp=" + (cloned.comparator() != null));
        System.out.println("viaSorted: " + viaSorted + " cmp=" + (viaSorted.comparator() != null));
        System.out.println("viaColl:   " + viaColl + " cmp=" + viaColl.comparator());
    }
}

How It Works

  1. Clone keeps custom order. Both cloned and viaSorted preserve reverseOrder() and keep [3, 2, 1].
  2. Overload choice matters. When the variable has static type Collection, Java picks TreeSet(Collection) instead of TreeSet(SortedSet).
  3. 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.

Next: comparator()

Return the custom Comparator, or null when using natural order.

comparator() 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.

11 people found this page helpful