Thursday, June 20, 2019

java - Bug in using Object.clone()



I have the next scenario:




I define an int[][] variable in my main class. int[][] matrix1 = new int[10][10] and i give it some values. I then call a method and i send this variable as a parameter to that method. Being an object it sends is by reference not by value, so inside the method, because i have to change the values contained by matrix1 but not affect the object after it returns from the method, i make a clone of it like so:



private void myMethod( int[][] matrix1 )
{
int[][] matrix1Clone = matrix1.clone();
//And next i do some changes to matrix1Clone
......
}



But the problem is that the changes i do to matrix1Clone also happen in matrix1. So it hasn't really created a clone of matrix1 object, but both variables point to the same object.



Why is this? I can't seem to figure it out. Why doesn't clone method work?



If you need more info, please ask. But i'm afraid this is about it, can't really give you more, but maybe i could try.



I might be missing something, but i can't figure out what...



Thanks.




EDIT



Sorry, made a typo. It's late hre and i'm tired. I'm using clone method indeed, that's why i'm confused as it's not working :(.


Answer



Try clone it using clone() http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/Object.html#clone%28%29



private void myMethod( int[][] matrix1 )
{
int[][] matrix1Clone = matrix1.clone();
}



or, copy all of the values using a loop



EDIT: Api for clone() says it should return a copy of the object, but behavior might be different depending on which object's beeing cloned. Try iterating over the array as an alternative. Since it's a 2d array, you need a nested loop:



for(int i=0; i  for(int j=0; j    old[i][j]=copy[i][j];



where old is the "original array" and copy is the copy


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...