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
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
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.
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())
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.
A side note: if your elements are immutable across the object graph - you don't need to clone them.