[英]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
的引用是相同的。 我以為我是復制元素,為什么指針一樣? 我該怎么做才能解決這個問題?
matrix
是static
所以所有的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.