Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Cloning

 
Angela Narain
Ranch Hand
Posts: 327
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,
I am not able to get the real essence of cloning an object ?
What is meant by deep copying and shallow copying
w.r.t. to cloning..
Can someone explain it to me, with an example..
 
Dave Vick
Ranch Hand
Posts: 3244
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Angela
A shallow copy would be just copying the reference(s) of an object to another variable, so that both variables reference the same object.
In a deep copy you actually make copys of the object(s) and assign them to the variable.
For example: say you have two arrays of ints arr1 and arr2. In a shallow copy you would assign each index of arr2 to reference the same object as the cooresponding index in arr1. both would point to the same object.
In a deep copy you create new objects to be referenced by arr2 instead of just having them reference the same object.
Hope that helps
Dave
 
Manfred Leonhardt
Ranch Hand
Posts: 1492
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Angela,
A deep copy is one that results in a totally separate object in memory that has the exact same state as the original. It kind of performs a 'new' function and populate the newer object with the state of the original. I can't give you a good example, because I don't know which class implements cloneable and performs a deep copy.
A shallow copy is one that results in some objects in memory being shared between the new and original objects. A good example of this would be the vector class.
<br /> When the above code is completed we have in memory:<br /> v1.1 --> 0
v1.2 --> 1
v1.3 --> 2
v1.4 --> 3
Now we can perform a cloning: v2 = v1.clone();
This results in the following (in memory):
v1.1 --> 0 <-- v2.1<br /> v1.2 --> 1 <-- v2.2<br /> v1.3 --> 2 <-- v2.3<br /> v1.4 --> 3 <-- v2.4
In this case, Integer is immutable so it won't be a big problem. But if the objects being referenced where not immutable, then if we change the state of v1.1 we would also be changing the state of v2.1!
Regards,
Manfred.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic