Java Utility Library

Java IdentityHashMap - clone() Method



The java.util.IdentityHashMap.clone() method returns a shallow copy of this identity hash map 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.IdentityHashMap.clone() method returns a shallow copy of the given map.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a identity hash map
    IdentityHashMap<Integer, String> Map1 = new IdentityHashMap<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 Object Map2
    Object Map2 = Map1.clone();

    //print the content of Map2
    System.out.print("Map2 contains: "+ Map2);  
  }
}

The output of the above code will be:

Map1 contains: {101=John, 102=Marry, 104=Jo, 103=Kim}
Map2 contains: {101=John, 102=Marry, 104=Jo, 103=Kim}

❮ Java.util - IdentityHashMap