0

I have the following codes for building a node:

public class Node {
    int state[][];
    String totalPath;
    int gn;
    int hn;
    int fn;
    boolean isLeaf;
    Node parentNode;
    int zeroX;
    int zeroY;
}

assume that I have constructed a node: Node currentNode = new Node();

but when I do this:

int subState[][] = currentNode.state;
switcher = subState[ycheck-1][xcheck];
subState[ycheck-1][xcheck] = 0;
subState[ycheck][xcheck] = switcher;

why is it that when i print substate[][] and currentNode.state[][], it appears that both 2D arrays are the same? isn't it supposed to work like this: substate[][] changes but currentNode.state[][] stays the same? why is it that every change i do to substate[][], the same is done to currentNode.state? is there a workaround for this?

thanks to those who will answer!

2 Answers2

0

it appears that both 2D arrays are the same

Because there are not two of them, there's only one of them. This line:

int subState[][] = currentNode.state;

...gives you a reference to the currentNode.state array, not a copy of it. Exactly the way that this code:

Map<String, String> m1 = new HashMap<String, String>();
Map<String, String> m2 = m1;
m1.put("one", "uno");
System.out.println(m2.get("one"));

...shows "uno", because m1 and m2 refer to the same map object.

Since you're changing the state of the object (array), you see that change regardless of which reference you look at the object through.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

When you do this in java arrFoo = new array; arrBar = arrFoo what happens is that both arrFoo and arrBar look at the same memory reference. This will mean that any changes done to one array will be implicitly done to the other.

Take a look at this previous SO post for more information.

Community
  • 1
  • 1
npinti
  • 51,780
  • 5
  • 72
  • 96
  • @JennyMelody: I have updated my answer to point to another answer with a more robust solution. I would recommend that over my previous recommendation. – npinti Feb 16 '15 at 13:17
  • int subState[][] = new int [3][]; subState[0] = currentNode.state[0].clone(); subState[1] = currentNode.state[1].clone(); subState[2] = currentNode.state[2].clone();... this ALSO WORKS!!! :D thanks!!! – JennyMelody Feb 16 '15 at 13:38
  • @JennyMelody: Please take a look at the most upvoted answer in the question I linked to in my answer. That should help you sovle the problem you are after. – npinti Feb 16 '15 at 13:40
  • @JennyMelody: Glad it worked for you. That being said, I would still recommend the approach in the linked question. `Clone` can be a bit messy sometimes ;). – npinti Feb 16 '15 at 13:43
  • basically, .clone() only "clones" a 1D array, so we have to copy the rows one by one!!! thanks for the help @npinti :D :D :D – JennyMelody Feb 16 '15 at 13:44