簡體   English   中英

如何在Java中的對象內復制2D數組?

[英]How can I copy a 2D Array inside an object in 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) ,對一塊板進行的任何更改都會影響另一塊板。 我復制了單獨的原始元素,但對於兩個板,對matrix的引用是相同的。 我以為我是復制元素,為什么指針一樣? 我該怎么做才能解決這個問題?

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.

更改

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

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

static表示此數組只有一個實例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM