Search code examples
javaa-star

Changes made to a local variable is linked to a node?


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!


Solution

  • 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.