Re: confusion of array clone() method



you can find out what clone() does to arrays by adding an assertion:
int[][] tt = (int[][]) tr_seq.clone();
assert( tt != tr_seq );

if clone doesn't do the job for arrays, you can write your own
copy_array static method or see if there already is such a thing in the
Java API.


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.

Sun

.



Relevant Pages

  • Re: problems with dup and clone...
    ... I have tried both dup and clone to copy the default objects but I always ... which reinitalised the instance arrays to and fix'ing the newly ... this program is a log scanner and I generate a class for each ...
    (comp.lang.ruby)
  • Re: Is clone a member function for array types?
    ... I believe that if you clone a multi-dimensional array, ... Actually I think that a deep clone of arrays would have been the ... in Java 6 java.util.Arrays has some very nice ... or used only in framework libraries/APIs. ...
    (comp.lang.java.programmer)
  • Re: Is clone a member function for array types?
    ... My guess is arrays are handled as a special case. ... This came up in a routine that was trying to do a generic clone. ... in Java 6 java.util.Arrays has some very nice methods for copying and resizing arrays. ...
    (comp.lang.java.programmer)
  • Re: TreeView Tag and clone
    ... now have routines that clone each object. ... I was fortunate that the arrays ... "DalePres" wrote: ...
    (microsoft.public.dotnet.languages.csharp)