Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Deep copy vs. shallow copy

 
James Brooks
Gunslinger
Ranch Hand
Posts: 165
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 34671
367
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
James Brooks
Gunslinger
Ranch Hand
Posts: 165
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1282
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Nicholas Jordan
Ranch Hand
Posts: 1282
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

[ January 30, 2008: Message edited by: Nicholas Jordan ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic