File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes CLONE Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "CLONE" Watch "CLONE" New topic


thomas davis
Ranch Hand

Joined: Feb 01, 2003
Posts: 207
What is shallow clonning and deep clonning?
How do I implement deep clonning and shalow clonning? :roll: :roll:
Igor Ko
Ranch Hand

Joined: Jun 24, 2002
Posts: 90

if we have shallow clone of instance a1 - a2 it will have values
{ sb1, 1 }, where sb1 the reference to the same instance of StringBuffer,
that has in a1.

So if you now change the StringBuffer in a1, it will be changed also
in a2.

If it is deep clone of a1 - a3, it will have other instance of StringBuffer
(with the same saved value "abcd"). So now if you change StringBuffer in
a1, a2 still have the same value "abcd".

By default java make shallow clone.
Jorge Phillips
Ranch Hand

Joined: Jun 03, 2001
Posts: 43
Think of a data structure as a tree. A shallow clone clones the root of the tree and shares the subtrees of the original tree's root. A deep clone is a recursive copy, i.e. all data structure components in the clone are copies of those in the original. In this case every non-leaf node in the tree would be a copy of the corresponding node in the original. Thus the name shallow vs deep.

Btw this terminology comes from LISP where you could do shallow and deep copies of lists. In this case the shallow copy copied only the top-level of the original list and the deep copy all levels of same.
Dirk Schreckmann

Joined: Dec 10, 2001
Posts: 7023
Note that this topic has been discussed a few times around these parts before. If you're interested in reading a few more explanations, I'd suggest trying a quick search on this and the intermediate forums. (The search page link is at the top right of this page.)

[How To Ask Good Questions] [JavaRanch FAQ Wiki] [JavaRanch Radio]
I agree. Here's the link:
subject: CLONE
It's not a secret anymore!