I’m doing an algorithm in like this:
public int[][] moveLeft(int m[][], int[] index){
Puzzle x = new Puzzle(m);
System.out.println(x);
int[][] p = m;
int temp = p[index[0]][index[1]];
p[index[0]][index[1]] = p[index[0]][index[1]-1];
p[index[0]][index[1]-1] = temp;
return p;
}
To be more specific, what i’m trying to do is to change the position of certain values and return the new matrix, but when i’m debuging, i noted that the value “m” also changues, even when im doing changes to the value p. What is wrong here?
Here is your culprit:
Once you do this,
pandmrefer to the same exact object, because arrays in Java are reference objects. Any change top‘s content will be reflected inm, becausepandmare two different names for a single object.If you need
pto be a copy ofm, you should do it explicitly. Here is a link to an answer showing you how it is done.