2

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().

user1837293
  • 1,466
  • 3
  • 16
  • 30
  • I'm not sure, but from the documentation it doesn't sound like arraycopy is recursive- it would copy the outermost array, but not recursively copy inner arrays of a multidimensional array. You may need to roll your own. – Gabe Sechan Feb 04 '13 at 20:58

1 Answers1

1

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;
} 
jenzz
  • 7,239
  • 6
  • 49
  • 69
  • Well actually the resulting (multidimensional) copy is (correctly) produced by arraycopy (as well as by clone(). The problem however is that it turns out to be a copy by reference instead of by value as I expected. – user1837293 Feb 05 '13 at 11:20
  • Could a copy constructor ([link](http://stackoverflow.com/questions/2427883/clone-vs-copy-constructor-which-is-recommended-in-java/)) help and how in this case? – user1837293 Feb 05 '13 at 14:56