How to copy an array

The reference for arrayCopy() 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]);.

2 Likes