Last Updated : 06 Aug, 2025
The clone() method of the HashMap class in Java is used to create a shallow copy of the specified HashMap. The method returns a new HashMap that contains the same key-value mappings as the original HashMap.
Example 1: Here, we will use the clone() method to clone a HashMap of Integer keys and String values.
Java
// Mapping String values to Integer keys
import java.util.HashMap;
public class GFG {
public static void main(String[] args) {
// Create a HashMap and add
// key-value pairs
HashMap<Integer, String> hm = new HashMap<>();
hm.put(1, "Java");
hm.put(2, "C++");
hm.put(3, "Python");
// Print the original HashMap
System.out.println("Original HashMap: " + hm);
// Clone the HashMap
HashMap<Integer, String> cl =
(HashMap<Integer, String>) hm.clone();
// Print the cloned HashMap
System.out.println("Cloned HashMap: " + cl);
}
}
Original HashMap: {1=Java, 2=C++, 3=Python} Cloned HashMap: {1=Java, 2=C++, 3=Python}
Explanation: In the above example, the clone() method creates a shallow copy of the HashMap. Both "hm" and "cl" contain the same key-value pairs.
To know more about Shallow copy and Deep copy refer this article: Shallow copy and Deep copy.
Syntax of HashMap clone() Methodpublic Object clone()
Points to Remember:
Example 2: Here, we will use the clone() method to clone a HashMap of String keys and Integer values.
Java
// Mapping Integer Values to String Keys
import java.util.*;
public class GFG {
public static void main(String[] args) {
// Creating an empty HashMap
HashMap<String, Integer> hm = new HashMap<String, Integer>();
// Mapping string keys to integer values
hm.put("Java", 1);
hm.put("C++", 2);
hm.put("Python", 3);
// Print and display the HashMap
System.out.println("Original HashMap: " + hm);
// Clone the HashMap
HashMap<String, Integer> cl
= (HashMap<String, Integer>) hm.clone();
System.out.println("Cloned HashMap: " + cl);
}
}
Original HashMap: {Java=1, C++=2, Python=3} Cloned HashMap: {Java=1, C++=2, Python=3}
Important Points:
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4