Clone: Deep Copy VS Shallow Copy

Hi, here is some explain about the difference between two operations.

I like to think of shallow/deep cloning in terms of parents and children. Shallow cloning copies the parent but shares the same children, whereas deeping cloning duplicates parents and children.

For example, if a parent A has 100 children objects, then a shallow clone would create a second parent B with references to the exact same children. In total 1 new object reference would be created. So if then modified parent A's children, parent B's children would be affected since they are shared.

With deep cloning, when I created parent B all the 100 children would also be copied. So this would amount to 101 new objects and modifying parent A's children would not affect parent B's children. Think of the performance difference between creating one object versus 101, which is why deep cloning is definitely a more expensive call.(primitives are never shared, objects are always shared in shallow cloning). [10x for Scott Selikoff ]

some example in java:

public class A {
public int i = 10;
public Object anObject;

public A() {
super();
}
public A cloneShallow() {
A a = new A();
a.i = this.i;
a.anObject = this.anObject;
return a;
}
public A cloneDeep() {
A a = new A();
a.i = this.i;
a.anObject = new Object();
// a.anObject.setParam(this.anObject.getParam());
return a;
}
מודעות פרסומת
מאת chenreuven פורסם ב-Java

להשאיר תגובה

הזינו את פרטיכם בטופס, או לחצו על אחד מהאייקונים כדי להשתמש בחשבון קיים:

הלוגו של WordPress.com

אתה מגיב באמצעות חשבון WordPress.com שלך. לצאת מהמערכת / לשנות )

תמונת Twitter

אתה מגיב באמצעות חשבון Twitter שלך. לצאת מהמערכת / לשנות )

תמונת Facebook

אתה מגיב באמצעות חשבון Facebook שלך. לצאת מהמערכת / לשנות )

תמונת גוגל פלוס

אתה מגיב באמצעות חשבון Google+ שלך. לצאת מהמערכת / לשנות )

מתחבר ל-%s