clone - In Java, what is a shallow copy? -
java.util.Calendar.clone () returns "a new calendar with the same properties" and returns "returns" This shallow copy of this calendar ".
This is not a shallow copy as the answer has been tagged to the question language-agnostic, Java language does not follow the agnostic definition As I stepped through the code, I see that the structure and the elements are copied to this new object, the cave
What is a shallow copy in Java?
Is it different from a Java deep copy (if it exists)?
A shallow copy just copies the values of references given in the class, copies a deep copy values given: < / P>
class Foo {private bar myBar; ... public foo shallow (copyright) (Foo newFoo = new Foo ()); NewFoo.myBar = myBar; New Return;} Public Foo deepCopy () {Foo newFoo = new Foo (); NewFoo.myBar = myBar.clone (); // or newer bar (mayabara) or merchandise dip copy or ... take new afoo; }} Foo Miefu = New Foo (); Foo SFu = MaiFhu.Salopi (); Foo dfu = myFoo.deepCopy (); MyFoo.myBar == sFoo.myBar = & gt; True myFoo.myBar.equals (sFoo.myBar) = & gt; True myFoo.myBar == dFoo.myBar = & gt; ** False ** myFoo.myBar.equals (dFoo.myBar) = & gt; True is the shallow copy of the same reference ( ==
) in this case and deep copy has only one parallel reference (.equals ()). )
).If any change is done for the value of the shallow copy reference, then copy reflects that change because it shares the same context. If there is a deeper change in the value of the copy reference, then the copy does not reflect that change because it does not share the same context.
C-ism
Int A = 10; // init int & amp; B = A; // shallow - copies reference c = a; // deep - copies VALUE ++ a;
Result:
a is 11 * b 11c 10
Comments
Post a Comment