Re: arrays and cloning, where is it described?
Andreas Leitgeb wrote:
It seems to be quite a basic thing, but I found myself
unsure about how it works, and where it is described.
(I didn't find it in JLS nor in the description of
Cloneable or Object.clone() in the javadoc)
According to JLS, arrays are Serializable and Cloneable,
and for multidimensional arrays, the JLS says:
" A clone of a multidimensional array is shallow,
" which is to say that it creates only a single
" new array. Subarrays are shared..
I'm not sure if this should be understood to imply
shallowness also in my case. Why would it have to
explicitly mention multidimensional arrays otherwise?
If I want to deep-copy an array of some Cloneable class,
what would be the best way to do it?
I'd be glad about answers, but even more I'd be glad
about pointers to any of sun's java-documents (jls,
api), where this behaviour or some "deepCopy" method
for arrays of cloneable types is directly described.
Is array's clone/copy altogether the wrong way, and
do I need to create a new array and fill it with
clones of each element, myself?
PS: In my task at hand I do not need to worry about
compiletime/runtime-type: they're the same.
The key to understanding this is to accept that Java does not really
have multidimensional arrays. It does have arrays whose elements are of
another array type, and sometimes pretends they are multidimensional
arrays, but not to the extent of making one work consistently as though
it were a single array with multiple dimensions.
Thus "new int[3][4]" is a three element array. Each element is a
reference to a four element array of int.
Cloning it creates a new three element array. Element n of the new array
refers to the same int[4] as element n of the original.
Patricia