[英]How can I copy a 2D Array inside an object in Java?
I've defined a class as follows: 我已经定义了一个类如下:
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
}
So here's my problem: when I try to make a copy, like myBoard.copy(otherBoard)
, any changes made to one board affect the other. 所以这就是我的问题:当我尝试制作副本时,例如myBoard.copy(otherBoard)
,对一块板进行的任何更改都会影响另一块板。 I copied in individual primitive elements, and yet the reference to matrix
is the same for both Boards. 我复制了单独的原始元素,但对于两个板,对matrix
的引用是相同的。 I thought I was copying elements, why are the pointers the same? 我以为我是复制元素,为什么指针一样? What can I do to fix this? 我该怎么做才能解决这个问题?
matrix
is static
so all the Board
objects share the same. matrix
是static
所以所有的Board
对象都是相同的。
Remove the static
to have each Board
have its own matrix. 移除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.
Change 更改
private static char[][] matrix = new char[SIZE][SIZE];
to 至
private char[][] matrix = new char[SIZE][SIZE];
static
means that there is only one instance of this array. static
表示此数组只有一个实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.