Here, the shallow copy means the keys and values are not copied. Instead, references to keys/values are copied. To learn more about the shallow copy, visit Java Shallow Copy.
The syntax of the clone() method is:
hashmap.clone()
Here, hashmap is an object of the HashMap class.
clone() Parameters
The clone() method does not take any parameters.
clone() Return Value
- returns a copy of the
HashMapinstances (objects)
Example 1: Make a Copy of HashMap
Output
HashMap: {Java=14, JavaScript=1, Python=3}
Cloned HashMap: {Java=14, JavaScript=1, Python=3}
In the above example, we have created an hashmap named languages. Notice the expression,
(HashMap<String, Integer>)languages.clone()
Here,
languages.clone()- returns a copy of the object languages(HashMap<String, Integer>)- converts object returned byclone()into a hashmap ofStringtype key andIntegertype values (To learn more, visit Java Typecasting)
Example 2: Print the Return Value of clone()
Output
Prime Numbers: {Five=5, Two=2, Three=3}
Return value of clone(): {Five=5, Two=2, Three=3}
In the above example, we have created an hashmap named primeNumbers. Here, we have printed the value returned by clone().
Note: The clone() method is not specific to the HashMap class. Any class that implements the Clonable interface can use the clone() method.