0

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?

tshepang
  • 12,111
  • 21
  • 91
  • 136
chntgomez
  • 2,058
  • 3
  • 19
  • 31
  • can you not debug and look at where/when m changes – Sean F Sep 20 '12 at 01:12
  • what is Puzzle x = new Puzzle(m); doing? – user710502 Sep 20 '12 at 01:13
  • Ok first of all, puzzle its just an object holding a matrix, done that for testing purposes, the moment when m starts "imitating" p happens at line 6, when i switch the positions in "p", the debugger shows that m switches positions too – chntgomez Sep 20 '12 at 01:16

2 Answers2

1

Here is your culprit:

int[][] p = m;

Once you do this, p and m refer to the same exact object, because arrays in Java are reference objects. Any change to p's content will be reflected in m, because p and m are two different names for a single object.

If you need p to be a copy of m, you should do it explicitly. Here is a link to an answer showing you how it is done.

Community
  • 1
  • 1
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0

I think you should use :

int [][] p = new int[m.length][];
for(int i = 0; i < m.length; i++)
   p[i] = m[i].clone();

instead of int[][] p = m;

so that p and m refer to two different objects.

Ouadie
  • 13,005
  • 4
  • 52
  • 62