我試圖創建一個Object
(稱爲State
)的深層副本,以對其中一個實例進行修改,然後根據新的State
修改舊的State
。具有原始類型的Java克隆類
這裏是State
:
public class State implements Cloneable {
// 0: empty
// 1: white
// 2: black
private int[][] board;
private int player;
public State(int[][] board, int player) {
this.board = board;
this.player = player;
}
public int[][] getBoard() {
return board;
}
public int getPlayer() {
return player;
}
public void setBoard(int[][] board) {
this.board = board;
}
public void setPlayer(int player) {
this.player = player;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
然後,這裏是我如何努力和訪問:
State temp = (State) s.clone();
Action act = determineAction(temp);
doSomething(s, act);
s
是傳遞到方法的State
。在調用determineAction
之後,出於某種原因,s
中的board
與temp
一起被修改,即使它沒有通過......這是怎麼回事?不應該調用.clone()
克隆所有基元類型的實例,以便它們可以進行唯一修改?
這就是這個帖子提示:http://howtodoinjava.com/core-java/cloning/a-guide-to-object-cloning-in-java/
我掙扎明白爲什麼這會不會被複制深,爲什麼我修改temp
也將修改s
。
任何提示將不勝感激 - 謝謝!
編輯 - 對於任何人都好奇,這裏是固定的:
@Override
protected Object clone() throws CloneNotSupportedException {
State cloned = (State) super.clone();
int[][] clonedBoard = new int[8][8];
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
clonedBoard[i][j] = board[i][j];
}
}
cloned.setBoard(clonedBoard);
return cloned;
}
工作,非常感謝你! – midwestcode