How to deep copy an irregular 2D array

后端 未结 7 1797
情深已故
情深已故 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:53

    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.

提交回复
热议问题