File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes Deep copy vs. shallow 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 "Deep copy vs. shallow copy" Watch "Deep copy vs. shallow copy" New topic
Author

Deep copy vs. shallow copy

James Brooks
Gunslinger
Ranch Hand

Joined: Aug 17, 2006
Posts: 165
OK, so why does it matter? I understand the difference between the two (effectively creating a pointer, versus setting the variables equal), but my book does not state why deep copy may be better. Can anyone provide me with a response?


Hello. My name is Inigo Montoya. You killed my father. Prepare to die.
Jeanne Boyarsky
author & internet detective
Marshal

Joined: May 26, 2003
Posts: 31079
    
163

Patrick,
Suppose you have the following class.


The caller of Copy has a reference to the original list. With a shallow copy, the caller's changes are seen by Copy and Copy's changes are seen by the caller. This can introduce some subtle side effects.


[Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Blogging on Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, OCAJP, OCPJP beta, TOGAF part 1 and part 2
James Brooks
Gunslinger
Ranch Hand

Joined: Aug 17, 2006
Posts: 165
So, are you saying that this would add the item to both lists? Also, is there a functional difference (taking away the syntactic sugar) between Object.getCopy()/Object.makeCopy(), and clone()? Thanks!
Nicholas Jordan
Ranch Hand

Joined: Sep 17, 2006
Posts: 1282
Jeanne has deep knowledge, so I will leave it to the OO'rs to explain it in OO terminology.

A shallow copy just makes another one, without transferring ( copying ) the values. A deep copy does something along the lines of for each item in source collection, set value in new collection to same as source collection.

This may involve the new operartor, many fundamental classes that are often used allow a reference to same kind as a constructor paramater and result in a totally new object which will not pass-through to the source complex object.

Anything other than a primitive would likely be a complex object, most any instance of a class is.


"The differential equations that describe dynamic interactions of power generators are similar to that of the gravitational interplay among celestial bodies, which is chaotic in nature."
Nicholas Jordan
Ranch Hand

Joined: Sep 17, 2006
Posts: 1282

[ January 30, 2008: Message edited by: Nicholas Jordan ]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Deep copy vs. shallow copy