Java TreeMap - clone() Method
The java.util.TreeMap.clone() method returns a shallow copy of this TreeMap instance. (The keys and values themselves are not cloned.)
Syntax
public Object clone()
Parameters
No parameter is required.
Return Value
Returns a shallow copy of this map.
Exception
NA
Example:
In the example below, the java.util.TreeMap.clone() method is used to create a clone of the given TreeMap.
import java.util.*; public class MyClass { public static void main(String[] args) { //create a treemap TreeMap<Integer, String> Map1 = new TreeMap<Integer, String>(); //populating Map1 Map1.put(101, "John"); Map1.put(102, "Marry"); Map1.put(103, "Kim"); Map1.put(104, "Jo"); //print the content of Map1 System.out.println("Map1 contains: "+ Map1); //create a copy of Map1 into Map2 Object Map2 = Map1.clone(); //print the content of Map2 System.out.println("Map2 contains: "+ Map2); } }
The output of the above code will be:
Map1 contains: {101=John, 102=Marry, 103=Kim, 104=Jo} Map2 contains: {101=John, 102=Marry, 103=Kim, 104=Jo}
❮ Java.util - TreeMap