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

Doubts in cloning concept.

 
Praveen Kumar
Ranch Hand
Posts: 133
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi ..

We have two types of cloning in java... Shallow and deep.

I know that if you use normal obj.clone() means we will get shallow one and to get deep , we need to go serialization.

I have doubt here ... When we want to go deep or shallow copy ...

Any links over that or explanation please ..

Thanks
Praveen
 
Martijn Verburg
author
Bartender
Posts: 3275
5
Eclipse IDE Java Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Praveen,

It depends on how much of the object's 'children' and 'relationships you want. Think of how many XML parsing libraries work, often they give you a choice, if you clone a Node they give you a basic copy of the Node (Attribute information, Id etc) or a copy of the Node including its entire tree structure.
 
Praveen Kumar
Ranch Hand
Posts: 133
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Martijn Verburg ,

Thanks for your reply ..

Could you give some other example which will explain more ?.

Because , i am not able to full picture.

Waiting for replies on this thread.
 
Nitesh Kant
Bartender
Posts: 1638
IntelliJ IDE Java MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Could you give some other example which will explain more ?

I can give it a shot ...

Let us take a web application that intends to provide some monitoring of the user sessions. Any administrator that logs into the system can view the current user sessions and what actions are being performed. The admin can take a snapshot of a user session for records.
Now, in order to take a snapshot the current state of the user session, which let us say is held by the object UserSession, needs to be copied. One can not use the same object because the user session is still active and hence can modify the state and hence making the snapshot dirty.
In such a scenario you need to take a "copy" of the entire user session object that may have contained objects till any depth. So, in this process you will scan the entire object and keep on copying any state of the object into a brand new instance. This process is called "deep copy" and when implemented as a clone, you might as well call it a deep clone.

Shallow copy can be useful in cases where the contained objects inside the copied object are immutable. So, there is no point in making a copy of these objects as they can not be changed. So, all you need to do is just create a new instance of the main object and be done with it.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic