tags:

views:

1218

answers:

4

Hello,

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

thanx

+4  A: 

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.

Michael Borgwardt
A: 

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

Oso
@Oso: What happens if e.getKey() or e.getValue() is another HashMap() or other object that also requires a deep-copy clone?
Grant Wagner
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
A: 

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.

Matthew Flaschen
+1  A: 

A side note: if your elements are immutable across the object graph - you don't need to clone them.

Fortyrunner