0

I'm trying to create a copy of a multi-dimensional array such that any modification to the new array will not affect the original array.

Here is my code:

public static int[][] getNextGenUniverse(int[][] validUniverse) {

    // Create a copy of the original array

    int[][] nextUniverse = new validUniverse[][];

    // Iterate through all the elements of the array

    for (int i = 0; i < nextUniverse.length; i++) {

      // Iterate through all the elements of the subarrays

      for (int j = 0; j < nextUniverse[i].length; j++) {

      nextUniverse[i][j] = validUniverse[i][j];
      }
    }
}

I'm having trouble declaring the length of the new array. Could someone help me please?

Elizabeth
  • 35
  • 1
  • 6
  • What do you mean with "any modification to the new array will not affect the original array"? Do you mean a shallow copy, where changing the new array's content does not change the other array's content, or do you mean a deep copy, where modifying objects _inside_ the new array do not modify ojects _inside_ the old array? – Mike 'Pomax' Kamermans Mar 28 '19 at 00:52
  • @Mike'Pomax'Kamermans I mean that changing an element of the new array will not change the corresponding element of the original array. – Elizabeth Mar 28 '19 at 00:57
  • there is still some ambiguity there, because "changing an element" usually means doing something like `arr[i].setValue()`, which will update _that object_ irrespective of what it's in. So did you mean a shallow copy, where the arrays are different, but they point to the same objects, or did you mean a deep copy, where _all the data involved_ gets copied, and immediately after copying there is already no relation between any of the data that either array points to? (e.g. "do you only want a copy of the library's indexing book, or do you want to copy the entire library including all the books") – Mike 'Pomax' Kamermans Mar 28 '19 at 01:08

1 Answers1

1

It should be the same length as validUniverse. And you can use Arrays.copyOf(int[], int) to perform the copy. Like,

public static int[][] getNextGenUniverse(int[][] validUniverse) {
    int[][] r = new int[validUniverse.length][];
    for (int i = 0; i < validUniverse.length; i++) {
        r[i] = Arrays.copyOf(validUniverse[i], validUniverse[i].length);
    }
    return r;
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • My code should be fine if I only change the declaration of the size of the new array? The Arrays.copyOf(int[], int) statement is optional, right? – Elizabeth Mar 28 '19 at 00:55
  • More or less, yes. However, Elliott's solution works for copying all matrices that aren't hellbent on destroying your computer. – Leftist Tachyon Mar 28 '19 at 01:01
  • @ElliotFrisch Don't you have to also initialize the length of the sub-arrays because I still get a NullPointerException – Elizabeth Mar 28 '19 at 13:00