Java HashMap clone() Method
The clone() method is used to create a shallow copy of a HashMap.
>
Extension:
A shallow copy only duplicates the pointers to objects, not the objects themselves. The new and old objects still share the same memory, so if one object changes this address, it will affect the other object.
A shallow copy contrasts with a deep copy, which copies an object completely from memory, creating a new region in the heap for the new object, and modifying the new object does not affect the original object.
The syntax for the clone() method is:
hashmap.clone()
Note: hashmap is an object of the HashMap class.
Parameter Description:
- None
Return Value
Returns a copy of the HashMap instance (object).
Example
The following example demonstrates the use of the clone() method:
Example
import java.util.HashMap;
class Main {
public static void main(String[] args) {
HashMap<Integer, String> sites = new HashMap<>();
sites.put(1, "Google");
sites.put(2, "tutorialpro");
sites.put(3, "Taobao");
System.out.println("HashMap: " + sites);
// Copy sites
HashMap<Integer, String> cloneSites = (HashMap<Integer, String>)sites.clone();
System.out.println("Cloned HashMap: " + cloneSites);
}
}
Executing the above program outputs:
HashMap: {1=Google, 2=tutorialpro, 3=Taobao}
Cloned HashMap: {1=Google, 2=tutorialpro, 3=Taobao}
In the above example, we created a HashMap named sites and used the clone() method to create a copy of sites.
Note the expression:
(HashMap<Integer, String>)sites.clone();
sites.clone() - Returns the copied sites object
(HashMap<Integer, String>) - Casts the returned object to a HashMap with keys of type Integer and values of type String.
Return Value of clone() Method:
Example
import java.util.HashMap;
class Main {
public static void main(String[] args){
// Create a hashmap
HashMap<String, Integer> primeNumbers = new HashMap<>();
primeNumbers.put("Two", 2);
primeNumbers.put("Three", 3);
primeNumbers.put("Five", 5);
System.out.println("Numbers: " + primeNumbers);
// Output the return value of clone() method
System.out.println("Return value of clone(): " + primeNumbers.clone());
}
}
Executing the above program outputs:
Prime Numbers: {Five=5, Two=2, Three=3}
Return value of clone(): {Five=5, Two=2, Three=3}
In the above example, we created a HashMap named primeNumbers, and the output is the return value of the clone() method.
Note: The clone() method is not specific to the HashMap class; any class that implements the Clonable interface can use the clone() method.