在 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".
这似乎不是所回答的浅拷贝此处 在 SO 上.这个问题被标记为与语言无关,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主义
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屋!