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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With