Java TreeMap clone() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
java.util.TreeMap

Definition

In Java, clone() returns a shallow copy of a TreeMap: a new tree with the same keys, the same values, and the same comparator. Adding or removing mappings in the copy does not affect the original, and vice versa.

"Shallow" means the key and value objects are not copied: both maps point to the same instances. That is harmless for immutable types such as String and Integer, but a mutable value like a List is shared. The copy is built in O(n) time from the already sorted entries.

An instance method of java.util.TreeMap, part of TreeMap since Java 1.2. A TreeMap keeps its key/value pairs sorted by key in a red-black tree, so lookups and updates take O(log n) time; it is not thread-safe.

Syntax

clone() returns Object, so a cast is needed.

Java
TreeMap<String, Integer> prices = new TreeMap<>();
@SuppressWarnings("unchecked")
TreeMap<String, Integer> copy = (TreeMap<String, Integer>) prices.clone();
CallWhat it does
(TreeMap<K, V>) map.clone()Shallow copy with the same comparator.
new TreeMap<>(map)Copy constructor; keeps the comparator when map is a SortedMap.
new TreeMap<>(); copy.putAll(map)Copy into a naturally ordered map.

The cast from Object to TreeMap<K, V> is unchecked, so the compiler warns unless you add @SuppressWarnings("unchecked"). The copy constructor new TreeMap<>(sortedMap) needs no cast and also keeps the comparator, which is why many developers prefer it.

Library declarations
Java
// java.util.TreeMap<K, V>
public Object clone()

// Overrides AbstractMap.clone()

Parameters

ParameterDescription
(none)clone takes no parameters.

Return Value

Return ValueDescription
ObjectA new TreeMap with the same mappings and comparator; cast it to TreeMap<K, V>.

Compare with Similar Methods

Ways to copy a TreeMap:

MethodHow it differs
putAll(map)Copies into an existing map, using its ordering.
comparator()Check which ordering a copy ended up with.
Collections.unmodifiableSortedMap()A read-only view instead of a copy.
HashMap.clone()The same shallow copy for a hash map.

Java Examples

Example 1 — Experiment on a Copy of a Price List

Changes to the clone's keys leave the original price list untouched.

Java
import java.util.TreeMap;

public class TreeMapCloneIndependent {
    public static void main(String[] args) {
        TreeMap<String, Integer> prices = new TreeMap<>();
        prices.put("tea", 3);
        prices.put("cake", 5);

        @SuppressWarnings("unchecked")
        TreeMap<String, Integer> draft = (TreeMap<String, Integer>) prices.clone();
        draft.put("soup", 6);
        draft.remove("tea");

        System.out.println("original: " + prices);
        System.out.println("draft: " + draft);
    }
}

How It Works

  1. A cast with a warning suppressed. clone() is declared to return Object, so the result is cast to TreeMap<String, Integer> and the unchecked warning is silenced on that one declaration.
  2. Own tree, own entries. Adding soup and removing tea change only draft; the copy has its own nodes.
  3. The original survives. prices still holds cake and tea, so the draft can be thrown away or adopted later.

Example 2 — A Cloned Map Shares Its List Values

Each team maps to an ArrayList; the clone holds the same list objects, not copies.

Java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.TreeMap;

public class TreeMapCloneShared {
    public static void main(String[] args) {
        TreeMap<String, List<String>> teams = new TreeMap<>();
        teams.put("blue", new ArrayList<>(Arrays.asList("Ana")));

        @SuppressWarnings("unchecked")
        TreeMap<String, List<String>> copy = (TreeMap<String, List<String>>) teams.clone();
        copy.get("blue").add("Ben");
        copy.put("red", new ArrayList<>());

        System.out.println("original: " + teams);
        System.out.println("copy: " + copy);
        System.out.println("same list object: " + (teams.get("blue") == copy.get("blue")));
    }
}

How It Works

  1. Mutating a shared value. copy.get("blue").add("Ben") changes the one list both maps point to, so Ben appears in the original too.
  2. New keys stay private. The "red" team was put only into copy, and teams never sees it.
  3. Identity proves it. == on the two "blue" lists is true: the clone copied the reference, not the list.

Example 3 — clone() Keeps a Reverse Comparator

The clone keeps the ranking order; copying with putAll into a plain TreeMap does not.

Java
import java.util.Comparator;
import java.util.TreeMap;

public class TreeMapCloneComparator {
    public static void main(String[] args) {
        TreeMap<Integer, String> ranks = new TreeMap<>(Comparator.reverseOrder());
        ranks.put(1, "bronze");
        ranks.put(3, "gold");
        ranks.put(2, "silver");

        @SuppressWarnings("unchecked")
        TreeMap<Integer, String> cloned = (TreeMap<Integer, String>) ranks.clone();
        TreeMap<Integer, String> rebuilt = new TreeMap<>();
        rebuilt.putAll(ranks);

        boolean sameOrdering = cloned.comparator() == ranks.comparator();
        System.out.println("clone: " + cloned);
        System.out.println("putAll copy: " + rebuilt);
        System.out.println("clone shares the comparator: " + sameOrdering);
    }
}

How It Works

  1. Order travels with the clone. cloned prints gold first, exactly like the reverse-ordered original.
  2. putAll uses the target's order. rebuilt was created without a comparator, so the same three entries come out in natural order, bronze first.
  3. The very same comparator. comparator() on the clone returns the original's comparator object, so the identity check is true.

Frequently Asked Questions

Shallow. The tree structure is new, but the key and value objects are shared with the original map.
clone() is declared to return Object, so you cast the result back to your TreeMap type. The cast is unchecked, which triggers a compiler warning.
Yes. The copy uses the same comparator object as the original, so it has the same ordering.
The copy constructor avoids the cast. With a SortedMap argument it keeps the comparator; with a plain Map argument it uses natural ordering.
Create a new TreeMap with the same comparator and put a new ArrayList copy of each value into it.

Next: comparator()

See which Comparator sorts the keys (null means 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.

10 people found this page helpful