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 and clonedArray 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 and clonedArray 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. 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 and clonedArray 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