Jasper_Li
Jasper_Li

Reputation: 244

Why can I change value in object A and object B would have the same effect although not identical in java?

I wrote some test code like this:

System.out.println(nineFive.getPotential()[0][0]); //not 1234
double[][] test = nineFive.getPotential().clone();
test[0][0] = 1234;
if(test != nineFive.getPotential()){
    System.out.println(nineFive.getPotential()[0][0]); //1234
}

Although the object I changed is test[0][0], object nineFive's value was changed simultaneously. I don't know why.

Upvotes: 1

Views: 69

Answers (2)

Tesseract
Tesseract

Reputation: 8139

A two dimensional array is an array of arrays. When you clone such an array what basically happens under the hood is this

static double[][] clone(double[][] array) {
  double[][] result = new double[array.length][];
  for(int i = 0; i < array.length; i++) {
    result[i] = array[i];
  }
  return result;
}

So the arrays contained inside the array are never copied. This is called in programming shallow copying, if you want to read more about it.

If you want to copy the whole array you could do it this way.

static double[][] copyArray(double[][] array) {
  double[][] result = new double[array.length][];
  for(int i = 0; i < array.length; i++) {
    result[i] = new double[array[i].length];
    for(int j = 0; j < array[i].length; j++) {
      result[i][j] = array[i][j];
    }
  }
  return result;
}

Upvotes: 4

Morn&#233;
Morn&#233;

Reputation: 16

I suggest reading through the following: Clone method for Java arrays

Note the following:

When the clone method is invoked upon an array, it returns a reference to a new array which contains (or references) the same elements as the source array.

Therefore, in your case, test will never == nineFive.getPotential(). However, they are referencing the same values in memory.

So, rather copy the array instead of cloning it.

Upvotes: 0

Related Questions