2
我定義一個類,如下所示:如何在Java中的對象內複製二維數組?
Public class Board{
public static final int SIZE = 4;
private static char[][] matrix = new char[SIZE][SIZE];
public Board(){
clear();//just fills matrix with a dummy character
}
public void copy(Board other){//copies that into this
for(int i = 0; i < SIZE; i++){
for(int j = 0; j < SIZE; j++){
matrix[i][j] = other.matrix[i][j];
}
}
}
//a bunch of other methods
}
因此,這裏是我的問題:當我嘗試做一個副本,像myBoard.copy(otherBoard)
,一個板所做的任何更改影響其他。我複製了各個原始元素,但對兩個Board的參考matrix
是相同的。我以爲我是複製元素,爲什麼指針是一樣的?我能做些什麼來解決這個問題?
謝謝你,我覺得很荒謬。我的CS老師不是很好,但你是 – LeoShwartz
@LeoShwartz謝謝你,但是太榮幸了。 ; d –