Search code examples
javaarraysdeep-copydimension

How to deep copy 2 dimensional array (different row sizes)


This is my first question in a community like this, so my format in question may not be very good sorry for that in the first place.

Now that my problem is I want to deep copy a 2 dimension array in Java. It is pretty easy when doin it in 1 dimension or even 2 dimension array with fixed size of rows and columns. My main problem is I cannot make an initialization for the second array I try to copy such as:

int[][] copyArray = new int[row][column]

Because the row size is not fixed and changes in each row index such as I try to copy this array:

int[][] envoriment = {{1, 1, 1, 1}, {0, 1, 6}, {1}};

So you see, if I say new int[3][4] there will be extra spaces which I don't want. Is there a method to deep copy such kind of 2 dimensional array?


Solution

  • I think what you mean is that the column size isn't fixed. Anyway a simple straightforward way would be:

    public int[][] copy(int[][] input) {
          int[][] target = new int[input.length][];
          for (int i=0; i <input.length; i++) {
            target[i] = Arrays.copyOf(input[i], input[i].length);
          }
          return target;
    }