user1837293
user1837293

Reputation: 1676

array copy by value fails (with clone() or arraycopy()) (Android, Java)

In order to make a copy of an array that holds a copy of the values instead of by reference I do the following:

int[][][] copy = {{{0}},{{0}},{{0,0}},{{0,0,0,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0,0,0}},{{0}},{{0,0}}};
System.arraycopy(spelerSpel, 0, copy, 0, spelerSpel.length);

then change a value IN THE COPY:

copy[SPELER_NUMMER][0][0] = baanSpelerNummer;

which results at that moment in the ORIGINAL (spelerSpel) array holding the same changed value, e.g.:

{{{4}},{{0}},{{0,0}},{{0,0,0,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0,0,0}},{{0}},{{0,0}}};

as the copy. I also tried .clone(), same result. What am I doing wrong?

By the way I target Android API 8, which doe not support Arrays.copyOf().

Upvotes: 2

Views: 735

Answers (1)

jenzz
jenzz

Reputation: 7269

System.arraycopy() does not support deep copies, but it does pretty well in terms of performance for simple arrays.

You can use it with some additional loops to create your own multi-dimensional arraycopy3d():

public int[][][] arraycopy3d(int[][][] array) {

     int[][][] copy = new int[array.length][][];

     for (int i = 0; i < array.length; i++) {
         copy[i] = new int[array[i].length][];
         for (int j = 0; j < array[i].length; j++) {
             copy[i][j] = new int[array[i][j].length];
             System.arraycopy(array[i][j], 0, copy[i][j], 0, array[i][j].length);
        }
    }

    return copy;
} 

Upvotes: 1

Related Questions