2013-03-22 70 views
0

我正在对气体粒子进行一些模拟。矩阵对象的翻译

我的问题是我做了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

这是因为你只复制你的二维数组的一个维度。所以你仍然引用相同的数组,因此在原始数组中修改它。

基本上,你有一个源对象[[1,2],[3,4]],当你做一个副本时,你正在将指针复制到[1,2][3,4]到一个新的数组中。

由于克隆做了一个浅拷贝(检查Does calling clone() on an array also clone its contents?),这最终会导致在内存中创建另一个完全相同的数组实例。