• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Cloning of Multidimensional Array

 
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Why is a clone of multidimensional array shallow?
Is the clone of singledimensional array shallow
or deep ?
Please Explain?
 
Ranch Hand
Posts: 3271
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Murgan Sub:
Why is a clone of multidimensional array shallow?
Is the clone of singledimensional array shallow
or deep ?
Please Explain?


A shallow clone simply means that references are copied, rather than new object created. Let's look at the following code (for a single-dimensional array):

As you can see, both origArray[0] and clonedArray[0] now reference the same object, the StringBuffer created at line 1. This is what is called a shallow copy. A deep copy is when, rather than copying a reference to the StringBuffer, a new StringBuffer would be created and placed into the cloned array. If that were the case, origArray[0] and clonedArray[0] would reference different objects (even though they would have the same contents originally) and the append at line 2 would have no impact on the object referenced by origArray[0].
When dealing with primitives, however, shallow copies are a little bit different. There's no reference to copy; only the primitive value itself is available, so it is copied to the new array. Let's look at some similar code:

As you can see, now origArray[0] and clonedArray[0] do not reference the same object because they aren't reference types at all. Rather, since we were cloning a primitive, the primitive value (just like the reference value above) is copied from one place to the other.
Multidimensional arrays behave exactly the same way. I sure hope this makes sense.
Corey
 
reply
    Bookmark Topic Watch Topic
  • New Topic