摘自 Herbert Schildt 关于 Java 的书的摘要
Cloning is a potentially dangerous action, because it can cause unintended side effects. For example, if the object being cloned contains a reference variable called obRef, then when the clone is made, obRef in the clone will refer to the same object as does obRef in the original. If the clone makes a change to the contents of the object referred to by obRef, then it will be changed for the original object, too.
因此,当对象被克隆时,请执行指向该对象的引用 原始对象也会被克隆,因此这些指向克隆的对象?
我对这一行感到困惑“…克隆中的obRef将引用 与原始 obRef 中的对象相同...”。
最佳答案
考虑对原始对象的引用与原始对象内的引用之间的区别。
假设你有一个对象 myObj
类型 MyClass
其中包含类型为 ArrayList
的字段命名为 myList。
当你构造这个对象时,myList 被初始化为 new ArrayList()
现在指向虚拟机堆中的一个对象。
现在假设您克隆 myObj
MyClass myClone = myObj.clone();
变量myClone
指向与 myObj 不同的对象。它们是两个不同的对象。然而,myList
myObj
内的字段指向堆中与 myList
相同的对象在myClone
。这是因为当你克隆时,引用是按原样复制的,没有 new ArrayList()
将一个单独的对象分配给 myList
在新对象中。
没有任何引用会自动更改,因此对旧 myObj
的任何引用仍指之。您对新对象的唯一引用是 myClone
直到您将其分配给其他变量。但myList
也是如此。 。所以这两个对象指向同一个ArrayList
。因此,如果其中一个添加了内容,另一个就会看到添加的值。
通常,这不是您所需要的。
关于java - Java 中的克隆对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26438552/