2016-03-27 59 views
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是相同的。我以爲我是複製元素,爲什麼指針是一樣的?我能做些什麼來解決這個問題?

回答

2

變化

private static char[][] matrix = new char[SIZE][SIZE]; 

private char[][] matrix = new char[SIZE][SIZE]; 

static意味着只有一個這種陣列的實例。

5

matrixstatic因此所有的Board對象共享相同。

刪除static以使每個Board都有其自己的矩陣。

private static char[][] matrix = new char[SIZE][SIZE]; <-- Because of this line 
matrix[i][j] = other.matrix[i][j];      <-- These two are the same. 
+1

謝謝你,我覺得很荒謬。我的CS老師不是很好,但你是 – LeoShwartz

+0

@LeoShwartz謝謝你,但是太榮幸了。 ; d –