How do I do a deep copy of a 2d array in Java?

前端 未结 6 1362
深忆病人
深忆病人 2020-11-22 02:07

I just got bit by using .clone() on my 2d boolean array, thinking that this was a deep copy.

How can I perform a deep copy of my bool

6条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-22 02:36

    I've managed to come up with a recursive array deep copy. It seems to work pretty well even for multi dimensional arrays with varying dimension lengths e.g.

    private static final int[][][] INT_3D_ARRAY = {
            {
                    {1}
            },
            {
                    {2, 3},
                    {4, 5}
            },
            {
                    {6, 7, 8},
                    {9, 10, 11},
                    {12, 13, 14}
            }
    };
    

    Here is the utility method.

    @SuppressWarnings("unchecked")
    public static  T[] deepCopyOf(T[] array) {
    
        if (0 >= array.length) return array;
    
        return (T[]) deepCopyOf(
                array, 
                Array.newInstance(array[0].getClass(), array.length), 
                0);
    }
    
    private static Object deepCopyOf(Object array, Object copiedArray, int index) {
    
        if (index >= Array.getLength(array)) return copiedArray;
    
        Object element = Array.get(array, index);
    
        if (element.getClass().isArray()) {
    
            Array.set(copiedArray, index, deepCopyOf(
                    element,
                    Array.newInstance(
                            element.getClass().getComponentType(),
                            Array.getLength(element)),
                    0));
    
        } else {
    
            Array.set(copiedArray, index, element);
        }
    
        return deepCopyOf(array, copiedArray, ++index);
    }
    

    EDIT: Updated the code to work with primitive arrays.

提交回复
热议问题