# How to copy an array

**URL:** <https://discourse.processing.org/t/how-to-copy-an-array/5170>\
**Category:** Beginners\
**Created:** [November 3, 2018, 11:45pm UTC](https://discourse.processing.org/t/how-to-copy-an-array/5170 "2018-11-03T23:45:53Z")\
**Posts on this page:** 11\
**Page:** 1

<div class="post-metadata">

**Author:** ![sLucas](https://avatars.discourse-cdn.com/v4/letter/s/4af34b/32.png) [@sLucas](https://discourse.processing.org/u/sLucas)\
**Post date:** [November 3, 2018, 11:45pm UTC](https://discourse.processing.org/t/how-to-copy-an-array/5170/1 "2018-11-03T23:45:53Z")

</div>

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

```auto
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.

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

```

Looking for a workaround.

Greetings, Lucas

---

<div class="post-metadata">

**Author:** ![Lexyth](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/lexyth/32/7403_2.png) [@Lexyth](https://discourse.processing.org/u/Lexyth)\
**Post date:** [November 3, 2018, 11:51pm UTC](https://discourse.processing.org/t/how-to-copy-an-array/5170/2 "2018-11-03T23:51:06Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![Jakub](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/jakub/32/2192_2.png) [@Jakub](https://discourse.processing.org/u/Jakub)\
**Post date:** [November 4, 2018, 12:03am UTC](https://discourse.processing.org/t/how-to-copy-an-array/5170/3 "2018-11-04T00:03:13Z")

</div>

To copy an array, you need to create a new array and copy the elements manually or with [arrayCopy()](https://processing.org/reference/arrayCopy_.html) or use [java.util.Arrays.copyOf](https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#copyOf(double%5B%5D,%20int)). 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).

---

<div class="post-metadata">

**Author:** ![GoToLoop](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/gotoloop/32/86_2.png) [@GoToLoop](https://discourse.processing.org/u/GoToLoop)\
**Post date:** [November 4, 2018, 12:23am UTC](https://discourse.processing.org/t/how-to-copy-an-array/5170/4 "2018-11-04T00:23:46Z")

</div>

Just directly invoke method [**clone()**](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Object.html#clone()) over the array container: 🤓

```auto
class Testos {
  final float[] a, b;

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

```

---

<div class="post-metadata">

**Author:** ![spambot9000](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/spambot9000/32/12568_2.png) [@spambot9000](https://discourse.processing.org/u/spambot9000)\
**Post date:** [July 2, 2021, 11:39pm UTC](https://discourse.processing.org/t/how-to-copy-an-array/5170/5 "2021-07-02T23:39:59Z")

</div>

@Lexyth, @Jakub : I haven’t explored the java methods yet, but arrayCopy() doesn’t seem to work on 2-d arrays. Does anyone know why this is?

```auto
void setup(){
  int[][] array1 = new int[2][5];
  // initialize array1  
  for(int j = 0; j < 5; j++){
    for(int i = 0; i < 2; i++){
      array1[i][j] = int(random(2*5));
    }
  }
  
  int[][] array2 = new int[2][5];  
  // initialize array2  
  for(int j = 0; j < 5; j++){
    for(int i = 0; i < 2; i++){
      array2[i][j] = int(random(2*5));
    }
  }

  println("array1 and array2 both initialized:");
  // print both arrays
  print("array1: ");
  for(int j = 0; j < 5; j++){
    for(int i = 0; i < 2; i++){
      print(array1[i][j] + " ");
    }
  } println();
  print("array2: ");
  for(int j = 0; j < 5; j++){
    for(int i = 0; i < 2; i++){
      print(array2[i][j] + " ");
    }
  } println();
  println();

  // arrayCopy() links array1 and array2!
  println("copy array1 to array2:");
  arrayCopy(array1, array2);

  // print both arrays
  print("array1: ");
  for(int j = 0; j < 5; j++){
    for(int i = 0; i < 2; i++){
      print(array1[i][j] + " ");
    }
  } println();
  print("array2: ");
  for(int j = 0; j < 5; j++){
    for(int i = 0; i < 2; i++){
      print(array2[i][j] + " ");
    }
  } println();
  println();
  

  println("new values generated for array1 only:");
  for(int j = 0; j < 5; j++){
    for(int i = 0; i < 2; i++){
      array1[i][j] = int(random(2*5));
    }
  }
  
  // print both arrays
  print("array1: ");
  for(int j = 0; j < 5; j++){
    for(int i = 0; i < 2; i++){
      print(array1[i][j] + " ");
    }
  } println();
  print("array2: ");
  for(int j = 0; j < 5; j++){
    for(int i = 0; i < 2; i++){
      print(array2[i][j] + " ");
    }
  } println();
  println();
  
  println("new values generated for array2 only:");
  for(int j = 0; j < 5; j++){
    for(int i = 0; i < 2; i++){
      array2[i][j] = int(random(2*5));
    }
  }
  
  // print both arrays
  print("array1: ");
  for(int j = 0; j < 5; j++){
    for(int i = 0; i < 2; i++){
      print(array1[i][j] + " ");
    }
  } println();
  print("array2: ");
  for(int j = 0; j < 5; j++){
    for(int i = 0; i < 2; i++){
      print(array2[i][j] + " ");
    }
  } println();
  println();

}

void draw(){}

```

---

<div class="post-metadata">

**Author:** ![Shwaa](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/shwaa/32/9696_2.png) [@Shwaa](https://discourse.processing.org/u/Shwaa)\
**Post date:** [July 4, 2021, 2:38am UTC](https://discourse.processing.org/t/how-to-copy-an-array/5170/7 "2021-07-04T02:38:58Z")

</div>

The reference for [arrayCopy()](https://processing.org/reference/arrayCopy_.html) states that it only copies references to each object in the base array (base array meaning the first brackets in any multidimensional array). If you have a 2D array, you have a base array storing other arrays. All `arrayCopy()` does is copy the _references_ to the other arrays into a new array. In your case, the references are referencing other 1D arrays storing ints. So, your new array is technically 2D, but any changes made to one reflect in the other because they are modifying the same _references_. If you want to deep copy arrays (create new references instead of reusing old ones), you will likely need to use a for loop to assign new values.

If you want to learn more about copying data in Java, read further.

If you are using primitives, like `int` or `float`, you can create new references by writing `array2[i][j] = array1[i][j];` because assigning primitives with = does not reuse references.  
If you are using Objects, like `String` or something else, using = _does_ reuse a reference. To overcome this, you need to create a new Object using the `new` operator. Because the `new` operator expects a constructor afterward, you likely need a copy constructor which deep copies all instance variables in the object. The String copy constructor looks like `String copy = new String(original);` and changes to copy will not affect the original. For a String array, you could use `array2[i][j] = new String(array1[i][j]);`.

---

<div class="post-metadata">

**Author:** ![spambot9000](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/spambot9000/32/12568_2.png) [@spambot9000](https://discourse.processing.org/u/spambot9000)\
**Post date:** [July 4, 2021, 10:48pm UTC](https://discourse.processing.org/t/how-to-copy-an-array/5170/8 "2021-07-04T22:48:34Z")

</div>

Thanks @Shwaa for the clarification and examples, especially the String copy constructor. That gives me something to work with. Cheers!

---

<div class="post-metadata">

**Author:** ![spambot9000](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/spambot9000/32/12568_2.png) [@spambot9000](https://discourse.processing.org/u/spambot9000)\
**Post date:** [August 15, 2021, 11:20pm UTC](https://discourse.processing.org/t/how-to-copy-an-array/5170/9 "2021-08-15T23:20:48Z")

</div>

Hi @GoToLoop,

What is the meaning of the three stops `...` in your above example? I don’t see anything in the Processing reference or the Java API.

Also, why use `final`? It seems that both arrays `a` and `b` are mutable.

Thanks in advance,  
sb9k

---

<div class="post-metadata">

**Author:** ![GoToLoop](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/gotoloop/32/86_2.png) [@GoToLoop](https://discourse.processing.org/u/GoToLoop)\
**Post date:** [August 16, 2021, 12:22am UTC](https://discourse.processing.org/t/how-to-copy-an-array/5170/10 "2021-08-16T00:22:50Z")

</div>

> [@spambot9000](#):
>
> What is the meaning of the three stops `...` in your above example?

That’s used for a variable argument parameter.  
It means we can pass an array or any number of arguments to that parameter.  
Such parameter behaves as an array inside its function.

> [@spambot9000](#):
>
> Also, why use `final` ? It seems that both arrays `a` and `b` are mutable.

Keyword `final` prohibits a variable to be re-assigned once it’s initialized.  
Keyword `final` doesn’t turn the object a variable points to immutable.

---

<div class="post-metadata">

**Author:** ![spambot9000](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/spambot9000/32/12568_2.png) [@spambot9000](https://discourse.processing.org/u/spambot9000)\
**Post date:** [August 16, 2021, 2:41am UTC](https://discourse.processing.org/t/how-to-copy-an-array/5170/11 "2021-08-16T02:41:05Z")

</div>

Thanks for the prompt reply, GoToLoop. You can see, perhaps, my confusion having read the following on the Processing reference page [final](https://processing.org/reference/final.html):

> Keyword used to state that a value, class, or method can’t be changed. If the **final** keyword is used to define a variable, the variable can’t be changed within the program.

The example code given there won’t even compile. Should the page be updated/expanded/clarified?  
[time passes]  
I see that the behaviour is supposed to different for arrays than for primitives.

Remaining questions:

- Why did you choose to use `final` is this example?
- What are the benefits?
- What are the drawbacks, if any?
- And, please, why use the intermediary assignment of `(a = arr)`?

Peace,  
sb9k

---

<div class="post-metadata">

**Author:** ![GoToLoop](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/gotoloop/32/86_2.png) [@GoToLoop](https://discourse.processing.org/u/GoToLoop)\
**Post date:** [August 16, 2021, 3:50am UTC](https://discourse.processing.org/t/how-to-copy-an-array/5170/12 "2021-08-16T03:50:45Z")

</div>

> [@spambot9000](#):
>
> Why did you choose to use `final` is this example?

I’m used to apply `final` to any variable I don’t want to be re-assigned.

> [@spambot9000](#):
>
> What are the benefits?

We can’t re-assign `final` variables by accident.

Also b/c a `final` variable got its value permanently sealed we can rest assured when its value is read that will be always the same.

> [@spambot9000](#):
>
> What are the drawbacks, if any?

Well, pretty much nothing really.

Of course we’ll have to remove the `final` keyword when we change our mind and need the variable to be re-assignable again.

> [@spambot9000](#):
>
> And, please, why use the intermediary assignment of `(a = arr)` ?

On C-based programming languages like Java & JS even the assignment `=` operator can be used within an expression.

I’ve just felt like to use that feature there.

I couldn’t do that in Python btW.

The way expression `b = (a = arr).clone();` works is 1st field _a_ receives the value of parameter _arr_.

Right after that method **clone()** is invoked on that same reference value creating a shallow copy of the array which field _a_ now references to.

Finally field _b_ receives the reference value of that cloned array.
