我正在研究一些气体颗粒的模拟。
我的问题是我制作了3个二维整数表。一个用于粒子的压力值,另一个用于描述粒子的x和y移动。
虽然我使用arraycopy并克隆它仍然以某种方式设法更改全局表中的值
private void translate() {
int [][] VectorXBuff = new int[500][500];
System.arraycopy(VectorX.clone(), 0, VectorXBuff, 0, VectorX.length);
int [][] VectorYBuff = new int[500][500];
System.arraycopy(VectorY.clone(), 0, VectorYBuff, 0, VectorX.length);
int [][] FieldBuff = new int[500][500];
System.arraycopy(FieldMatrix.clone(), 0, FieldBuff, 0, VectorX.length);
for (int y = 0; y < FieldMatrix.length; y++){
for (int x = 0; x < FieldMatrix.length; x++){
if(FieldBuff[x][y]!= 0 && FieldBuff[x][y]!= 9 ){
FieldBuff[x + VectorXBuff[x][y]][y + VectorYBuff[x][y]] = Integer.valueOf(FieldBuff[x][y]);
FieldBuff[x][y] = 0;
VectorXBuff[x + VectorXBuff[x][y]][y + VectorYBuff[x][y]] = Integer.valueOf(VectorXBuff[x][y]);
VectorYBuff[x + VectorXBuff[x][y]][y + VectorYBuff[x][y]] = Integer.valueOf(VectorYBuff[x][y]);
VectorXBuff[x][y] = 0;
VectorYBuff[x][y] = 0;
}
}
}
}
答案 0 :(得分:0)
这是因为您只复制二维数组的一个维度。因此,您仍然引用相同的数组,因此在原始数组中进行修改。
基本上,您有一个源对象[[1,2],[3,4]]
,当您执行复制时,您将指向[1,2]
和[3,4]
的指针复制到一个新数组中。
当克隆执行浅拷贝(检查Does calling clone() on an array also clone its contents?)时,这最终会重新生成只在内存中创建完全相同的数组实例的另一个数组。