How to deep copy an irregular 2D array

后端 未结 7 1795
情深已故
情深已故 2020-12-04 02:06

How can I deep copy an irregularly shaped 2D array in Java?

Ie.

int[][] nums =  {{5},
                 {9,4},
                 {1,7,8},
                      


        
7条回答
  •  春和景丽
    2020-12-04 02:57

    int[][] copy = new int[nums.length][];
    
    for (int i = 0; i < nums.length; i++) {
        copy[i] = new int[nums[i].length];
    
        for (int j = 0; j < nums[i].length; j++) {
            copy[i][j] = nums[i][j];
        }
    }
    

    You can replace the second loop with System.arraycopy() or Arrays.copyOf().

提交回复
热议问题