【问题标题】:How can I copy a 2D Array inside an object in Java?如何在 Java 中的对象内复制 2D 数组?
【发布时间】:2016-03-27 16:02:23
【问题描述】:

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

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),对一个板所做的任何更改都会影响另一个板。我复制了单独的原始元素,但对两个板的 matrix 的引用是相同的。我以为我在复制元素,为什么指针是一样的?我该怎么做才能解决这个问题?

【问题讨论】:

    标签: java arrays multidimensional-array


    【解决方案1】:

    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.
    

    【讨论】:

    • 谢谢,我觉得很可笑。我的 CS 老师并不出色,但你是
    • @LeoShwartz 谢谢,但太荣幸了。 ;D
    【解决方案2】:

    改变

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

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

    static 表示这个数组只有一个实例。

    【讨论】:

      猜你喜欢
      • 2012-02-26
      • 1970-01-01
      • 2016-06-10
      • 2013-02-28
      • 2020-10-06
      • 1970-01-01
      • 1970-01-01
      • 2015-02-15
      • 2023-02-17
      相关资源
      最近更新 更多