如何在Java中的对象内复制2D数组?

Leo*_*rtz 2 java arrays multidimensional-array

我已经定义了一个类如下:

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
}
Run Code Online (Sandbox Code Playgroud)

所以这就是我的问题:当我尝试复制时,例如myBoard.copy(otherBoard),对一个板的任何更改都会影响另一个板.我复制了各个原始元素,但matrix两个板的引用是相同的.我以为我是复制元素,为什么指针一样?我该怎么做才能解决这个问题?

Yas*_*jaj 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.
Run Code Online (Sandbox Code Playgroud)