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

一个人想着一个人 提交于 2019-11-26 21:22:57

问题


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?


回答1:


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;
}



回答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 ?




回答3:


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.




回答4:


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);
  }
}


来源:https://stackoverflow.com/questions/5563157/how-to-deep-copy-2-dimensional-array-different-row-sizes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!