Java HashMap clone()

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 HashMap instances (objects)

Example 1: Make a Copy of HashMap

import java.util.HashMap;

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

        // create HashMap
        HashMap<String, Integer> languages = new HashMap<>();

        languages.put("Java", 14);
        languages.put("Python", 3);
        languages.put("JavaScript", 1);
        System.out.println("HashMap: " + languages);

        // create copy of languages
        HashMap<String, Integer> cloneLanguages = (HashMap<String, Integer>)languages.clone();
        System.out.println("Cloned HashMap: " + cloneLanguages);
    }
}

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 by clone() into a hashmap of String type key and Integer type values (To learn more, visit Java Typecasting)

Example 2: Print the Return Value of clone()

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);

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