File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Cloning Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Cloning" Watch "Cloning" New topic
Author

Cloning

Angela Narain
Ranch Hand

Joined: Apr 14, 2001
Posts: 327
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

Joined: May 10, 2001
Posts: 3244
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


Dave
Manfred Leonhardt
Ranch Hand

Joined: Jan 09, 2001
Posts: 1492
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.
 
 
subject: Cloning
 
Similar Threads
session casting problem....
is there any way to pass objects throw http params ?
Cloning v/s Reference Copying
session casting problem....
How do you guard your arrays?