Java HashMap clone() Method

Java HashMap Java HashMap

The clone() method is used to copy a hashMap, which is a shallow copy.

Extension:

A shallow copy only copies the pointer to an object, not the object itself. The new and old objects still share the same memory, soif one of the objects changes this address, it will affect the other object.。。

The counterpart of shallow copy is deep copy. Deep copy copies an object completely from memory, opens a new area in heap memory to store the new object, andmodifying the new object will not affect the original object.。

The syntax of 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, "Example");
        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);
    }
}

The output of running the above program is:

HashMap: {1=Google, 2=Example, 3=Taobao}
Cloned HashMap: {1=Google, 2=Example, 3=Taobao}

In the above example, we created a HashMap named sites, and then used the clone() method in the code to copy a duplicate of sites.

Note the expression:

(HashMap<Integer, String>)sites.clone();
  • sites.clone() - returns the copied sites object
  • (HashMap<Integer, String>) converts the returned object into a HashMap, where its keys are of type Integer and its values are of type String.

The return value of the 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 the clone() method
        System.out.println("Return value of clone(): " + primeNumbers.clone());
    }
}

The output of running the above program is:

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 Cloneable interface can use the clone() method.

Java HashMap Java HashMap

Other Extensions