0

I'm working on some simulation of gas particles.

My problem is that I made 3 two-dimensional integer tables. One for pressure value of particle, and another two to describe x and y movement of particle.

Although I make arraycopy and clone it still somehow manage to change values in global table

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;
            }
        }
    }
}
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Lemonov
  • 476
  • 4
  • 17

1 Answers1

0

This is because you only copy one dimension of your two dimension array. So you are still referencing the same arrays and therefore modifying it in the original one.

Basically, you have a source object [[1,2],[3,4]] and when you do a copy you are copying the pointer to [1,2] and [3,4] into a new array.

As the clone does a shallow copy (check Does calling clone() on an array also clone its contents?) this in the end resumt to just creating another array of the exactly same instances of arrays in memory.

Community
  • 1
  • 1
benzonico
  • 10,635
  • 5
  • 42
  • 50