对局部变量所做的更改链接到节点?
Changes made to a local variable is linked to a node?
我有以下构建节点的代码:
public class Node {
int state[][];
String totalPath;
int gn;
int hn;
int fn;
boolean isLeaf;
Node parentNode;
int zeroX;
int zeroY;
}
假设我已经构建了一个节点:
Node currentNode = new Node();
但是当我这样做时:
int subState[][] = currentNode.state;
switcher = subState[ycheck-1][xcheck];
subState[ycheck-1][xcheck] = 0;
subState[ycheck][xcheck] = switcher;
为什么当我打印 substate[][] 和 currentNode.state[][] 时,两个二维数组看起来是一样的?它不应该像这样工作吗:substate[][] 改变但 currentNode.state[][] 保持不变?为什么我对 substate[][] 所做的每一次更改都对 currentNode.state 进行了同样的更改?有解决办法吗?
感谢那些会回答的人!
it appears that both 2D arrays are the same
因为没有两个,所以只有一个。这一行:
int subState[][] = currentNode.state;
...为您提供对 currentNode.state
数组的 reference,而不是它的 copy。正是这段代码的方式:
Map<String, String> m1 = new HashMap<String, String>();
Map<String, String> m2 = m1;
m1.put("one", "uno");
System.out.println(m2.get("one"));
...显示 "uno",因为 m1
和 m2
引用 相同的 地图对象。
由于您正在更改对象(数组)的状态,因此无论您通过哪个引用查看对象,您都会看到该更改。
当您在 java arrFoo = new array; arrBar = arrFoo
中执行此操作时,会发生 arrFoo
和 arrBar
查看相同的内存引用。这意味着对一个数组所做的任何更改都将隐式地对另一个数组进行。
查看 this 之前的 SO post 了解更多信息。
我有以下构建节点的代码:
public class Node {
int state[][];
String totalPath;
int gn;
int hn;
int fn;
boolean isLeaf;
Node parentNode;
int zeroX;
int zeroY;
}
假设我已经构建了一个节点:
Node currentNode = new Node();
但是当我这样做时:
int subState[][] = currentNode.state;
switcher = subState[ycheck-1][xcheck];
subState[ycheck-1][xcheck] = 0;
subState[ycheck][xcheck] = switcher;
为什么当我打印 substate[][] 和 currentNode.state[][] 时,两个二维数组看起来是一样的?它不应该像这样工作吗:substate[][] 改变但 currentNode.state[][] 保持不变?为什么我对 substate[][] 所做的每一次更改都对 currentNode.state 进行了同样的更改?有解决办法吗?
感谢那些会回答的人!
it appears that both 2D arrays are the same
因为没有两个,所以只有一个。这一行:
int subState[][] = currentNode.state;
...为您提供对 currentNode.state
数组的 reference,而不是它的 copy。正是这段代码的方式:
Map<String, String> m1 = new HashMap<String, String>();
Map<String, String> m2 = m1;
m1.put("one", "uno");
System.out.println(m2.get("one"));
...显示 "uno",因为 m1
和 m2
引用 相同的 地图对象。
由于您正在更改对象(数组)的状态,因此无论您通过哪个引用查看对象,您都会看到该更改。
当您在 java arrFoo = new array; arrBar = arrFoo
中执行此操作时,会发生 arrFoo
和 arrBar
查看相同的内存引用。这意味着对一个数组所做的任何更改都将隐式地对另一个数组进行。
查看 this 之前的 SO post 了解更多信息。