How to deep copy an irregular 2D array

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().

Leave a Comment