Reputation: 2128
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)?
Upvotes: 7
Views: 25028
Reputation: 37969
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;
}
Upvotes: 0
Reputation: 528
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());
Upvotes: 1
Reputation: 1232
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
.
Upvotes: 1
Reputation: 284836
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.
Upvotes: 0
Reputation: 346317
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.
Upvotes: 12