Java TreeMap.clone() example

In this java tutorial, You will learn how to use clone() method of TreeMap class.The clone() method is used to return a shallow copy of this TreeMap instance.But the keys and values themselves are not cloned.

Returns a shallow copy of this TreeMap instance.


public Object clone()


A shallow copy of this map.

Java TreeMap clone() example

  • Create TreeMap instance new TreeMap < Integer, String > ();
  • Add few elements in TreeMap e.g. students.put(1, "Pooja");
  • Print the TreeMap values.
  • students.clone(); It will return shallow copy of the TreeMap.
  • Print TreeMap clone copy elements.
package com.technicalkeeda;

import java.util.TreeMap;

public class App {
    public static void main(String args[]) {

        TreeMap < Integer, String > students = new TreeMap < Integer, String > ();

        students.put(1, "Pooja");
        students.put(2, "Ajit");
        students.put(3, "Yashwant");
        students.put(4, "Aditi");

        System.out.println("TreeMap values :- " + students);
        System.out.println("TreeMap after clone() :- " + students.clone());


TreeMap values :- {1=Pooja, 2=Ajit, 3=Yashwant, 4=Aditi}
TreeMap after clone() :- {1=Pooja, 2=Ajit, 3=Yashwant, 4=Aditi}