我正在尝试复制int father_state [] [],它是使用另一个Object类的.clone()方法复制到另一个相同类型的int son_state [] [],当我试图更改值时在son_state中,father_state的值也会改变。
public Node create_node_son(Node father_node, String action, int row, int column){
Node new_node= new Nodo();
int father_state[][] = father_node.state.clone();
int son_state[][] = father_state;
int aux;
new_node.setState(father_node.state);
/*SWAP of states*/
aux = new_node.state[father_node.pos_zero_y][nodo_padre.pos_zero_x];
new_node.estado[father_node.pos_zero_y][father_node.pos_zero_x]= son_state[row][column];
new_node.estado[row][column]=aux;
//nuevo_nodo = new Nodo(estado_hijo, columna, renglon, nodo_padre.costo+1, accion, nodo_padre);
/*Refresh the data*/
new_node.action=action;
new_node.cost=nodo_father.costo+1;
new_node.father=nodo_father;
new_node.pos_zero_x=cloumn;
new_node.pos_zero_y=row;
return new_node;
}
答案 0 :(得分:1)
更改子状态会导致父状态发生变化,因为两者都指向此处提到的同一对象:
int son_state[][] = father_state;
你应该克隆父亲的父亲状态,如下所述:
int father_state[][] = father_node.state.clone(); // new clone object
int son_state[][] = father_node.state.clone(); // new clone object
答案 1 :(得分:0)
我在另一篇文章中找到答案,我需要另一个复制功能
public static int[][] cloneArray(int[][] src) {
int length = src.length;
int[][] target = new int[length][src[0].length];
for (int i = 0; i < length; i++) {
System.arraycopy(src[i], 0, target[i], 0, src[i].length);
}
return target;
}