Java Utility Library

Java HashMap - clone() Method



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

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a hash map
    HashMap<Integer, String> Map1 = new HashMap<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, 103=Kim, 104=Jo}
Map2 contains: {104=Jo, 101=John, 102=Marry, 103=Kim}

❮ Java.util - HashMap