VOOZH about

URL: https://www.geeksforgeeks.org/java/hashmap-clone-method-in-java/

⇱ HashMap clone() Method in Java - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

HashMap clone() Method in Java

Last Updated : 6 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.


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.


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.
Comment