How can I deep copy an irregularly shaped 2D array in Java?
Ie.
int[][] nums = {{5},
{9,4},
{1,7,8},
I wrote this in Eclipse, tested it, came back and found that João had beaten me to almost exactly the same solution. I upvoted him, but here's mine for comparison. I guess it's instructive to see the very slight details people choose to do differently.
private static int[][] copy2d(int[][] nums) {
int[][] copy = new int[nums.length][];
for (int i = 0; i < copy.length; i++) {
int[] member = new int[nums[i].length];
System.arraycopy(nums[i], 0, member, 0, nums[i].length);
copy[i] = member;
}
return copy;
}
For extra credit, try writing one that copies an n-dimensional array where n is arbitrary.