Re: confusion of array clone() method



hyena wrote:
hi,

I just came across this situation that the cloned array linked to the original array and changes made to the clone also applied to the original one. I do not think I understand fully the description of deep clone/shallow clone concept and got a bit confused here.

code:
private int[][] decode(int[][] tr_seq) {
// translate the sequces into real travel times
int[][] tt = (int[][]) tr_seq.clone();
for(int i =0; i < tt.length; i++){
for(int j =0; j < tt[0].length; j++){
tt[i][j] = 100;
}
}
return tt;
}

tr_seq was changed after this method was called. I was assuming a clone is apart from the original object and has its own reference address. isn't it?

from java document ,

"Creates and returns a copy of this object. The precise meaning of "copy" may depend on the class of the object. The general intent is that, for any object x, the expression:
x.clone() != xwill be true".

this statement does not agree on this example.

could someone shed some light on this? Thanks.

The key issue is what constitutes an array. Java does not really have
multidimensional arrays. tr_seq is an array whose elements are
references to arrays.

clone makes a new array whose elements point to the same arrays as the
original.

For any i from 0 to tt.length-1, tt[i] and tr_seq[i] are identical. They
are either both null, or are pointers to the same array. Changes to an
element of an array they both reference apply regardless of whether you
find that array through tr_seq or tt.

Patricia
.



Relevant Pages

  • Re: Instances effecting each other?
    ... //Please note that if x and y are reference types, you will want to clone ... it will definitely return a reference to a new object. ... So in that case how can i take an instance in an array and create a new ... SceneChair chair2 = new SceneChair; ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: MemberwiseClone() doesnt like arrays?
    ... clone *also* contains a field that is a reference to the managed ... shallow clone on an object whose fields are references. ... and manually clone the array ... you have 2 arrays pointing to the same Customer objects, ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: MemberwiseClone() doesnt like arrays?
    ... separate array. ... will need to write Clone yourself, ... I have lots of classes inheriting from those ... classes, adding more members still. ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: arraylist copy
    ... Then what is the difference between CopyTo and Clone? ... >reference, than they grew apart. ... >A copyto makes a copy of the values in a one dimensional array. ...
    (microsoft.public.dotnet.languages.vb)
  • Re: arraylist copy
    ... Then what is the difference between CopyTo and Clone? ... > a reference, than they grew apart. ... > A copyto makes a copy of the values in a one dimensional array. ...
    (microsoft.public.dotnet.languages.vb)