更新时间:2023-01-17 16:35:12
实现可能涉及循环引用的深层副本的最简单方法是,如果您希望以后能够容忍对结构的更改,那么将使用 IdentityHashMap
和 IdentityHashSet
(来自这里)。如果要复制:
The easiest way to implement a deep copy that might involve circular references, if you want it to be tolerant of changes to the structure later, would be to use an IdentityHashMap
and an IdentityHashSet
(from here). When you want to copy:
IdentityHashMap< Object,Object>
,将源对象映射到它们的克隆。 IdentityHashSet< Object>
来跟踪当前所有的对象克隆的过程,但还没有完成。 IdentityHashMap
中查找它,看看您是否已克隆该位。如果有,请返回您在 IdentityHashMap
中找到的副本。 IdentityHashSet
查看您是否正在克隆您现在已达到的对象(因为循环引用)。如果你有,现在就把它设置为 null
,然后继续。 IdentityHashSet
,递归深度克隆它,然后当你完成递归调用时,将源/克隆对添加到 IdentityHashMap
,并将其从 IdentityHashSet 。 null
因为您遇到了循环引用而导致您挂起的引用。您可以同时浏览源和目标图。每当您在源图中找到一个对象时,请在 IdentityHashMap
中查找它,并找出它应映射到的内容。如果它存在于 IdentityHashMap
中,并且如果目标图形中当前 null
,则可以设置目标引用到你在 IdentityHashMap
中找到的克隆。IdentityHashMap<Object,Object>
, to map source objects to their clones.IdentityHashSet<Object>
to track all the objects that are currently in the process of being cloned, but haven't yet finished.IdentityHashMap
to see if you've already cloned that bit. If you have, return the copy that you find in the IdentityHashMap
.IdentityHashSet
to see if you're in the middle of cloning the object you've now reached (because of a circular reference). If you have, just set it to null
for now, and move on.IdentityHashSet
, recursively deep clone it, and then when you've finished the recursive call, add the source/clone pair to the IdentityHashMap
, and remove it from the IdentityHashSet
.null
references you left hanging because you encountered a circular reference. You can walk the graph of source and destination simultaneously. Whenever you find an object in the source graph, look it up in your IdentityHashMap
, and find out what it should map to. If it exists in the IdentityHashMap
, and if it's currently null
in the destination graph, then you can set the destination reference to the clone you find in the IdentityHashMap
.这将确保你不要将图形的相同部分克隆两次,但只要在图形中出现两次的对象,它总是以相同的参考结尾。这也意味着循环引用不会导致无限递归。
This will make sure you don't clone the same part of the graph twice, but always end up with the same reference whenever there's an object that appears twice in your graph. It will also mean that circular references don't cause infinite recursion.
使用 Identity
版本的要点是如果图中的两个对象与 .equals()
确定的相同,但由 == $ c $确定的不同实例c>,然后一个
HashSet
和 HashMap
会识别这两个,你最终会把所有东西加在一起不加入。只有在 == $ c c>。
The point of using the Identity
versions is that if two objects in your graph are the same as determined by .equals()
, but different instances as determined by ==
, then a HashSet
and HashMap
would identify the two, and you'd end up joining things together that shouldn't be joined. The Identity
versions will treat two instances as the same only if they're identical, i.e., the same as determined by ==
.
如果您想要完成所有这些但无需自己实现,您可以查看 Java深度克隆库。
If you want to do all this but without having to implement it yourself, you could have a look at the Java Deep Cloning Library.