• Post Reply Bookmark Topic Watch Topic
  • New Topic

Cloning of Multidimensional Array  RSS feed

 
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • 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
  • 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
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!