Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java HashMap - deep copy

I am just trying to find out the best solution how to make a deep copy of HashMap. There are no objects in this map which implement Cloneable. I would like to find better solution than serialization and deserialization.

like image 905
Smolda Avatar asked Oct 24 '12 12:10

Smolda


People also ask

How do I create a deep copy in HashMap?

Using Google's JSON Library Another way to clone a HashMap is to use Google's JSON library. In this method, first, convert the map to JSON string and JSON string back to a new map object. It works the same as the serialized object holds no reference to the original object on deserialization.

Can we clone HashMap in Java?

The Java HashMap clone() method makes the shallow copy of the hashmap and returns it. Here, the shallow copy means the keys and values are not copied. Instead, references to keys/values are copied. To learn more about the shallow copy, visit Java Shallow Copy.

How do I clone a HashMap?

Instead of iterating through all of the entries, we can use the putAll() method, which shallow-copies all of the mappings in one step: HashMap<String, Employee> shallowCopy = new HashMap<>(); shallowCopy. putAll(originalMap); We should note that put() and putAll() replace the values if there is a matching key.


1 Answers

Take a look at Deep Cloning, on Google Code you can find a library. You can read it on https://github.com/kostaskougios/cloning.

How it works is easy. This can clone any object, and the object doesnt have to implement any interfaces, like serializable.

Cloner cloner = new Cloner();
MyClass clone = cloner.deepClone(o);
// clone is a deep-clone of o

Be aware though: this may clone thousands of objects (if the cloned object has that many references). Also, copying Files or Streams may crash the JVM.

You can, however, ignore certain instances of classes, like streams et cetera. It's worth checking this library and its source out.

like image 78
stealthjong Avatar answered Oct 01 '22 12:10

stealthjong