Java – how to deeply copy 2-dimensional arrays (different row sizes)

This is my first question in such a community, so my format may not be very good. Sorry

Since my problem is that I want to deeply copy two-dimensional arrays in Java It is very easy to operate in 1 - or even 2 - dimensional arrays with fixed - size rows and columns My main problem is that I cannot initialize the second array I try to copy, for example:

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

Because the row size is not fixed and changes in each row index (for example, I try to copy this array):

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

So you see, if I say the new int [3] [4] will have extra space, I don't want it Is there a way to deeply copy this two-dimensional array?

Solution

I think you mean that the column size is not fixed In any case, a simple and clear method is:

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;
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>