Reputation: 902
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.
Upvotes: 19
Views: 47227
Reputation: 11617
This is not easy, we are using some sort of workaround:
1) convert the map to json string. (for example, using Google Gson)
2) convert the json string back to map.
Do note that there is performance issue, but this is kind of easiest way.
Upvotes: 3
Reputation: 11093
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.
Upvotes: 13
Reputation: 1344
I don't think it can be implemented in a generic way.
For now, I'd propose to re-write your question in a less general way
Upvotes: 3