What are the differences between shallow and deep copies?

  • Thread starter Thread starter Chromium
  • Start date Start date
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
4 replies · 27K views
Chromium
Messages
56
Reaction score
0
Hey Everyone,

Could someone confirm whether or not this "picture" of a shallow and deep copy is accurate? Since I've only programmed in Java, my code/pseudo-code will be java-ish.

Shallow Copy

Object Reference String Object
String s 10010101010

In this case, a String object has a String reference s "pointing" to it.


Object Reference String Object
String s 10010101010
t

In this case, the same String object has two object references pointing to it. In
actuality, t is just a copy of s. So in short, a shallow copy is just a copy of the
object reference. Ultimately, you have two object references pointing to the
same object.

Deep Copy

Object Reference String Object
String s 10010101010

The String object still only has reference pointing to it.

Object Reference String Object
String s 10010101010
String t 10010101010

Now there is a completely new and different String object (however, it is a copy
of the original String object. The new object reference points to a completely
distinct (yet exactly alike) object.



Feel free to criticize this "picture" of shallow v. deep copies if it is vague, unclear,
plain wrong, etc...(but please be gentle!)
 
Last edited:
Physics news on Phys.org
Your table formatting confuses me a little but otherwise yes, that is exactly correct.
 
Sorry about that, I'm not sure why it turned out like that. I went back to edit it, but the tables are still the same, oh well. By the way, thanks for reassuring me that I indeed understand deep and shallow copies!
 
Chromium said:
Sorry about that, I'm not sure why it turned out like that. I went back to edit it, but the tables are still the same, oh well. By the way, thanks for reassuring me that I indeed understand deep and shallow copies!

Wrap your text in [ CODE ] tags:

Code:
[B]Object   Reference[/B] 
String   s          10010101010
 
Yes, or put another more useful way - shallow copies can be overwritten by modifying the source object, deep copies are not changed by modifying the original source object.
Shallow copies allow you to shoot yourself in the foot more easily, in other words.