Is there java utility that does clone()
method for HashMap
such that it does copy of the map elements not just the map object (as the clone()
in HashMap
class)?
-
A side note: if your elements are immutable across the object graph - you don't need to clone them. – Fortyrunner Jun 15 '09 at 21:52
5 Answers
What about other objects referred to in the elements? How deep do you want your clone?
If your map elements don't have any deep references and/or everything is Serializable
, you can serialize the map via ObjectOutputStream
into a ByteArrayOutputStream
and then deserialize it right away.
The only other alternative is to do it manually.

- 342,105
- 78
- 482
- 720
The SO question Deep clone utility recommendation is similar to this one, and has an answer that may be helpful to you.
To summarize, they recommend using the Cloning library from Google Code. From personal experience, it deep-copies HashMap
s. It can even clone things that aren't Cloneable
.

- 1
- 1

- 1,212
- 1
- 12
- 26
Once you know your key/value pair elements are cloneable:
HashMap<Foo, Bar> map1 = populateHashmap();
HashMap<Foo, Bar> map2 = new HashMap<Foo, Bar>();
Set<Entry<Foo, Bar>> set1 = map1.entrySet();
for (Entry<Foo, Bar> e : l)
map2.put(e.getKey().clone(), e.getValue().clone());
-
2@Oso: What happens if e.getKey() or e.getValue() is another HashMap() or other object that also requires a deep-copy clone? – Grant Wagner Jun 15 '09 at 21:18
-
well... this is a simple hashmap clone routine. I am actually assuming that the objects are cloneable, so the deepnes will be solved by the key/value objects themselves. In order to deepclone a hashmap without assuming serializable/cloneable, I think reflection would be a way (still not sure if true). – Oso Jun 16 '09 at 14:40
Often copy should be deep. Here is an example how to "deep copy"
Map<Integer, ArrayList<Integer>>
code:
public static Map<Integer, ArrayList<Integer>> deepCopyMapIntList
(Map<Integer, ArrayList<Integer>> original) {
Map<Integer, ArrayList<Integer>> copy = new HashMap<>(original.size());
for (int i : original.keySet()) {
ArrayList<Integer> list = original.get(i);
copy.put(i, (ArrayList<Integer>) list.clone());
}
return copy;
}

- 36,676
- 11
- 141
- 113
Take a look at the deepClone method at http://www.devdaily.com/java/jwarehouse/netbeans-src/db/libsrc/org/netbeans/lib/ddl/impl/SpecificationFactory.java.shtml . It is not generic, but it includes several built-in types (including HashMap itself, recursively), and can obviously be extended.

- 278,309
- 50
- 514
- 539