2016-03-27 55 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 –