HashMap clone() Method in Java
Last Updated : 13 Dec, 2024
Improve
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.
// 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);
}
}
Output
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() Method
public Object clone()
- Parameters: The method does not take any parameters.
- Return Value: The clone() method returns a shallow copy of the HashMap.
Points to Remember:
- The clone is shallow means the keys and values themselves are not cloned, but references to them are copied.
- Changes to mutable objects inside the HashMap will reflect in both the original and the cloned HashMap.
Example 2: Here, we will use the clone() method to clone a HashMap of String keys and Integer values.
// 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);
}
}
Output
Original HashMap: {Java=1, C++=2, Python=3} Cloned HashMap: {Java=1, C++=2, Python=3}
Important Points:
- The same operation can be performed with any type of mappings with variation and combination of different data types.
- clone() method does the shallow copy. But here the values in the original and cloned hashmap will not affect each other because primitive data type is used.