File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes How to do �shallow copy� and �deep copy�? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "How to do �shallow copy� and �deep copy�?" Watch "How to do �shallow copy� and �deep copy�?" New topic

How to do �shallow copy� and �deep copy�?

Chetan Parekh
Ranch Hand

Joined: Sep 16, 2004
Posts: 3640
While reading API of Object.clone (), I cam across following paragraph.

�The method clone for class Object performs a specific cloning operation. First, if the class of this object does not implement the interface Cloneable, then a CloneNotSupportedException is thrown. Note that all arrays are considered to implement the interface Cloneable. Otherwise, this method creates a new instance of the class of this object and initializes all its fields with exactly the contents of the corresponding fields of this object, as if by assignment; the contents of the fields are not themselves cloned. Thus, this method performs a "shallow copy" of this object, not a "deep copy" operation.�

I am not clear, How to do �shallow copy� and �deep copy�?
[ May 25, 2006: Message edited by: Chetan Parekh ]

My blood is tested +ve for Java.
Jeff Albertson
Ranch Hand

Joined: Sep 16, 2005
Posts: 1780

There is no emoticon for what I am feeling!
Manesh Kumar
Ranch Hand

Joined: Mar 21, 2006
Posts: 94
In simplest say, in the shallow copy, objects within the array will not be cloned. Only the array object is cloned.
When an array object is cloned, the duplicate array object will have same references to objects as in original array.

In deep cloning, each object in the array will be cloned including array object. Both array objects (original and cloned) will have different references to the objects. You need to write code for implementing deep copy like what Jeff Albertson has given.

But shallow copy does not hold good for array of primitive types.

Nikhil Goel
Ranch Hand

Joined: Jul 11, 2003
Posts: 32
Here is avery good artcle for the same

This is inline with all the above posts and mentions the 3 different techniques for copying.
Chetan Parekh
Ranch Hand

Joined: Sep 16, 2004
Posts: 3640
Thanks you very much all, my doubts has been cleared !!
I agree. Here's the link:
subject: How to do �shallow copy� and �deep copy�?
It's not a secret anymore!