![]() |
VOOZH | about |
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.
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.
public Object clone()
Points to Remember:
Example 2: Here, we will use the clone() method to clone a HashMap of String keys and Integer values.
Original HashMap: {Java=1, C++=2, Python=3}
Cloned HashMap: {Java=1, C++=2, Python=3}
Important Points: