Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deep copy an irregular 2D array

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?)

like image 778
Sean McDaid Avatar asked Jan 07 '09 10:01

Sean McDaid


2 Answers

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

like image 105
Joao da Silva Avatar answered Sep 30 '22 17:09

Joao da Silva


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.

like image 37
slim Avatar answered Sep 30 '22 15:09

slim