Easy Tutorial
❮ Java Character Dir Create ❯

Java HashMap clone() Method

Java HashMap

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:

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&lt;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&lt;Integer, String> cloneSites = (HashMap&lt;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&lt;Integer, String>)sites.clone();

Return Value of clone() Method:

Example

import java.util.HashMap;

class Main {
    public static void main(String[] args){

        // Create a hashmap
        HashMap&lt;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.

Java HashMap

❮ Java Character Dir Create ❯