在Java中,什么是浅层副本? [英] In Java, what is a shallow copy?
问题描述
java.util.Calendar.clone()返回...具有相同属性的新日历并返回此日历的浅表副本。
java.util.Calendar.clone() returns "...a new Calendar with the same properties" and returns "a shallow copy of this Calendar".
这似乎不是一个浅的副本,因为回答在这里。该问题被标记为语言无关, Java似乎不遵循语言无关的定义。当我逐步执行代码时,我注意到结构和元素被复制到这个新对象,而不仅仅是语言无关的结构。
This does not appear to be a shallow copy as answered here on SO. That question is tagged language-agnostic, Java does not seem to follow the language agnostic definition. As I step through the code I notice that the structure and the elements are copied to this new object, more than the language agnostic structure only.
在Java中,什么是浅拷贝?
In Java, what is a shallow copy?
它与Java深层拷贝(如果存在)有什么不同?
How does it differ from a Java deep copy (if that exists)?
推荐答案
浅拷贝只是复制类中引用的值。深拷贝会复制值。给定:
A shallow copy just copies the values of the references in the class. A deep copy copies the values. given:
class Foo {
private Bar myBar;
...
public Foo shallowCopy() {
Foo newFoo = new Foo();
newFoo.myBar = myBar;
return newFoo;
}
public Foo deepCopy() {
Foo newFoo = new Foo();
newFoo.myBar = myBar.clone(); //or new Bar(myBar) or myBar.deepCopy or ...
return newFoo;
}
}
Foo myFoo = new Foo();
Foo sFoo = myFoo.shallowCopy();
Foo dFoo = myFoo.deepCopy();
myFoo.myBar == sFoo.myBar => true
myFoo.myBar.equals(sFoo.myBar) => true
myFoo.myBar == dFoo.myBar => **false**
myFoo.myBar.equals(dFoo.myBar) => true
在这种情况下,浅拷贝具有相同的引用( ==
)和深拷贝只有一个等价的引用( .equals()
)。
In this case the shallow copy has the same reference (==
) and the deep copy only has an equivalent reference (.equals()
).
如果对浅复制引用的值进行了更改,则副本会反映该更改,因为它共享相同的引用。如果对深度复制的引用的值进行了更改,则副本不会反映该更改,因为它不共享相同的引用。
If a change is made to the value of a shallowly copied reference, then the copy reflects that change because it shares the same reference. If a change is made to the value of a deeply copied reference, then the copy does not reflect that change because it does not share the same reference.
C-ism
int a = 10; //init
int& b = a; //shallow - copies REFERENCE
int c = a; //deep - copies VALUE
++a;
结果:
a is 11
*b is 11
c is 10
这篇关于在Java中,什么是浅层副本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!