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

前端 未结 4 1754
一向
一向 2020-12-06 13:24

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

相关标签:
4条回答
  • 2020-12-06 13:48

    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;
    }
    
    0 讨论(0)
  • 2020-12-06 13:55

    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 ?

    0 讨论(0)
  • 2020-12-06 13:59

    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.

    0 讨论(0)
  • 2020-12-06 14:11

    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);
      }
    }
    
    0 讨论(0)
提交回复
热议问题