How can I deep copy an irregularly shaped 2D array in Java?
Ie.
int[][] nums = {{5},
{9,4},
{1,7,8},
{8,3,2,10}}
I'm unable to use Arrays.arrayCopy()
for some reason (versioning?)
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().
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With