Java HashMap - deep copy

冷暖自知 提交于 2019-11-27 09:04:31
stealthjong

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.

I don't think it can be implemented in a generic way.

  • If you have the chance to simply implement clone, I'd go that way.
  • A bit more complex is creating a type map, where you look up some kind of clone implmentation class based on the class of each object
  • When the objects might form a Directed Acyclic Graph, I'd in general keep a Map from the original to the clone of every object I've ever seen, and check if I've already made it
  • When you have a general graph, the problem gets really nasty. You might have strange constraints of the object creation order, it might even be impossible when you have final fields.

For now, I'd propose to re-write your question in a less general way

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!