How to deep copy an irregular 2D array

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

    Here is a simple convenient way to copy 2 dimensional arrays (compatible with DEEP copy) :

    public static char[][] cloneArray(char[][] array){
     char[][] copy = new char[array.length][];
     for(int i = 0 ; i < array.length ; i++){
      System.arraycopy(array[i], 0, copy[i] = new char[array[i].length], 0, array[i].length);
     }
     return copy;
    }
    

    plz note that you simple have to change array type to anything else, like int

提交回复
热议问题