What is the TreeMap.clone() function in Java?

In this shot, we will learn how to use the TreeMap.clone() method in Java.

Introduction

The TreeMap.clone() method is present in the TreeMap class inside the java.util package.

It is used to return the shallow copy of the given TreeMap.

Parameter

The TreeMap.clone() method doesn’t accept any parameters.

Return

The TreeMap.clone() method returns the copy of TreeMap on which it is called. The returned object is of type Object. The Object class is the parent class of all sub-classes in Java.

Let’s understand with the help of an example. Suppose that a TreeMap contains the following key-value pairs:

  • Key: 1, Value: Educative
  • Key: 5, Value: Learn Coding
  • Key: 2, Value: Python
  • Key: 27, Value: C++

Using the TreeMap.clone() method and storing the result in another TreeMap object, we get a copy of the original TreeMap object.

Code

import java.util.*;
class Main
{
public static void main(String[] args)
{
TreeMap<Integer, String> h1 = new TreeMap<Integer, String>();
h1.put(1, "Educative");
h1.put(5, "Python");
h1.put(2, "Java");
h1.put(27, "Learn Coding");
h1.put(9, "C++");
System.out.println("The TreeMap is: " + h1);
Object h2 = h1.clone();
System.out.println("The clone of specified TreeMap is: " + h2);
}
}

Explanation

  • In line 1, we imported the required package.

  • In line 2, we made the Main class.

  • In line 4, we made a main() function.

  • In line 6, we declared a TreeMap consisting of keys of type Integer and values of type String.

  • From lines 8 to 12, we inserted values in the TreeMap by using the TreeMap.put() method.

  • In line 14, we displayed the original TreeMap.

  • In line 16, we used the TreeMap.clone() method to create the clone of TreeMap and stored it in a variable of type Object.

  • In line 18, we displayed the cloned TreeMap with a message.

So, this is how we can use the TreeMap.clone() method to return a shallow copy of the given TreeMap.

Free Resources