Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Deep Copy v. Shallow Copy

  1. Jan 2, 2008 #1
    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: Jan 2, 2008
  2. jcsd
  3. Jan 2, 2008 #2
    Your table formatting confuses me a little but otherwise yes, that is exactly correct.
     
  4. Jan 2, 2008 #3
    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!
     
  5. Jan 2, 2008 #4

    DaveC426913

    User Avatar
    Gold Member

    Wrap your text in [ CODE ] tags:

    Code (Text):
    [B]Object   Reference[/B]
    String   s          10010101010
     
  6. Jan 3, 2008 #5

    jim mcnamara

    User Avatar
    Science Advisor
    Gold Member

    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.
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?



Similar Discussions: Deep Copy v. Shallow Copy
Loading...