English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
The Java HashMap clone() method creates a shallow copy of the hash table and returns it.
Here, shallow copy means not to copy the keys and values. Instead, it copies the reference to the keys/values reference.
The syntax of the clone() method is:
hashmap.clone()
clone() method has no parameters.
Return a copy of the HashMap instance (object)
import java.util.HashMap; class Main { public static void main(String[] args){ // Create a 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 a copy of languages HashMap<String, Integer> cloneLanguages = (HashMap<String, Integer>)languages.clone(); System.out.println("Copy of HashMap: ", + cloneLanguages); } }
Output Result
HashMap: {Java=14, JavaScript=1, Python=3} Copy of HashMap: {Java=14, JavaScript=1, Python=3}
In the above example, we created a hash map named languages. Note the expression
(HashMap<String, Integer>)languages.clone()
Here,
languages.clone() - Return a copy of the object languages
(HashMap<String, Integer>) - Convert the object returned by clone() to a HashMap with String type keys and Integer type values (for more information, please visitJava Type Conversion)
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 clone() return value System.out.println("clone() return value: ", + primeNumbers.clone()); } }
Output Result
Prime Numbers: {Five=5, Two=2, Three=3} clone() return value: {Five=5, Two=2, Three=3}
In the above example, we created a hash map named primeNumbers. Here, we printed the value returned by clone().
NoteThe :clone() method is not specific to the HashMap class. Any class that implements the Clonable interface can use the clone() method.