6

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?

icedwater
  • 4,701
  • 3
  • 35
  • 50

4 Answers4

10

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;
}
Asaf
  • 6,384
  • 1
  • 23
  • 44
  • Awesome, this is what I seek in general. Thanks for all of the answers they all helped me :) –  Apr 06 '11 at 08:32
2

You don't have to initialize both dimensions at the same time:

int[][] test = new int[100][];
test[0] = new int[50];

Does it help ?

pgras
  • 12,614
  • 4
  • 38
  • 46
  • Oh this information will help. I never thought of initializing dimensions in different time –  Apr 06 '11 at 08:21
1

Java 8 lambdas make this easy:

int[][] copy = Arrays.stream(envoriment).map(x -> x.clone()).toArray(int[][]::new);

You can also write .map(int[]::clone) after JDK-8056051 is fixed, if you think that's clearer.

Jeffrey Bosboom
  • 13,313
  • 16
  • 79
  • 92
-2

You might need something like this:

public class Example {
  public static void main(String[] args) {

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

    int[][] copyArray = new int[envoriment.length][];
    System.arraycopy(envoriment, 0, copyArray, 0, envoriment.length);
  }
}
Shankar Raju
  • 4,356
  • 6
  • 33
  • 52
  • 1
    The code you are proposing is shallow-copying, isn't it? The arraycopy will copy each value of the environment array into the new one. It is: it will copy the references to the original rows. It's not going to copy the sub-arrays. – helios Apr 06 '11 at 08:16
  • @rlibby and @Helios, are you guys sure it does shallow copy? I thought is does a deep copy. In that case let me revisit. I might be wrong. Thanks for pointing it out. – Shankar Raju Apr 06 '11 at 08:47
  • 1
    it is shallow copy, you are copying references to one dimensional arrays, you can check by adding this after your code: envoriment[2][0] = 5; and check copyArray[2][0] is now also 5 – pgras Apr 06 '11 at 09:13