📅  最后修改于: 2023-12-03 14:41:41.620000             🧑  作者: Mango
In Java, HashMap is a class that implements the Map interface and provides mapping between keys and values. A HashMap stores its entries in an array of the type Entry<K,V> where K is the type of keys and V is the type of values. Each Entry is a linked list node containing information about the key-value pair and the next Entry in the list.
To create a copy of a HashMap, you can use the clone method defined in the Object class. This method creates a shallow copy of the HashMap, which means that only the references to the keys and values are copied, not the objects themselves. If you modify an object in the original HashMap, the corresponding entry in the cloned HashMap will also be modified. In order to create a deep copy of the HashMap with independent key-value pairs, you need to create new objects for each entry.
Here is an example of using the clone method to create a shallow copy of a HashMap:
HashMap<String, Integer> scores1 = new HashMap<>();
scores1.put("Alice", 95);
scores1.put("Bob", 85);
HashMap<String, Integer> scores2 = (HashMap<String, Integer>) scores1.clone();
scores2.put("Charlie", 90);
System.out.println(scores1); // {Alice=95, Bob=85}
System.out.println(scores2); // {Alice=95, Bob=85, Charlie=90}
In this example, we create a HashMap scores1
with two entries and then create a shallow copy of it using the clone method. We add a new entry to scores2
and print the contents of both HashMaps. As you can see, the new entry is only added to the cloned HashMap and not the original one.
To create a deep copy of the HashMap, you can use the putAll method to copy all the entries to a new HashMap:
HashMap<String, Integer> scores1 = new HashMap<>();
scores1.put("Alice", 95);
scores1.put("Bob", 85);
HashMap<String, Integer> scores2 = new HashMap<>();
scores2.putAll(scores1);
scores2.put("Charlie", 90);
System.out.println(scores1); // {Alice=95, Bob=85}
System.out.println(scores2); // {Alice=95, Bob=85, Charlie=90}
In this example, we create a new HashMap scores2
and copy all the entries of scores1
using the putAll method. We add a new entry to scores2
and print the contents of both HashMaps. As you can see, the new entry is only added to the cloned HashMap and not the original one, but the key-value pairs in scores2
are independent of those in scores1
.
In summary, the clone method creates a shallow copy of a HashMap, which means that the keys and values are not duplicated but shared between the original and cloned HashMaps. For a deep copy that creates independent key-value pairs, you can use the putAll method to copy all entries to a new HashMap.