How to copy an array


#1

A bug has been found… (No bug has been found (edit))
Explanation follows

void setup() {
  double[] a = {1, 2, 3};
  double[] b = {1, 2, 3};
  for (double print : b) {
    print(print + ", ");
  }
  println();
  b = new Testos(a).running();
  for (double print : b) {
    print(print + ", ");
  }
  println();
}

public class Testos {
  double[] a;
  double[] b;
  Testos(double[] a) {
    this.a = a;
    this.b = a;
  }
  public double[] running() {
    for (int i = 0; i < this.a.length; i++) {
      this.a[i] = this.b[i]+5;
    }
    return this.b;
  }
}

Output:

1.0, 2.0, 3.0,
6.0, 7.0, 8.0,

Expected Output:

1.0, 2.0, 3.0,
1.0, 2.0, 3.0,

I think the expected output has to be correct, because the class Testos has 2 vars a and b. b is assigned to a at the very beginning. There a is 1.0, 2.0, 3.0. Then b is not touched any more in any way. It should still be 1.0, 2.0, 3.0. However, it isn’t. The returned b has been changed. It is now equal to a, a being 6.0, 7.0, 8.0.

My estimation is that the double passed to the constructor dereferences b and references it to a. Consequently, invoking changes made to a also to b, eventhough these changes are not desired.

Testos(double[] a) {
  this.a = a;
  this.b = a;
}

Looking for a workaround.

Greetings, Lucas


#2

Nope, it‘s right. It‘s because arrays are only referenced by assigning them with a = b.
Example :
double[] a = {1.0, 2.0, 3.0};
double[] b = a;
b[0] = 100.0;
//a = {100.0,2.0,3.0}
//b = {100.0, 2.0, 3.0}

You can use b = arrayCopy(a); to avoid this.


#3

To copy an array, you need to create a new array and copy the elements manually or with arrayCopy() or use java.util.Arrays.copyOf. Otherwise both a and b refer to the same instance, as you found out yourself. This also applies to all objects (exception are primitives like int, boolean, or float, which are copied).


#4

Just directly invoke method clone() over the array container: :nerd_face:

class Testos {
  final float[] a, b;

  Testos(final float... arr) {
    b = (a = arr).clone();
  }
}

Differentiating Array definitions