如何在Java中进行二维数组的深层复制?

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

我只是在2d boolean数组上使用.clone()感到有点困惑,认为这是一个深层副本。

如何执行boolean[][]阵列的深层副本?

我应该遍历它并执行一系列System.arraycopy吗?


是的,您应该遍历2D布尔数组以进行深复制。如果您使用的是Java 6,也请查看java.util.Arrays#copyOf方法。

我建议使用Java 6的下一个代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
public static boolean[][] deepCopy(boolean[][] original) {
    if (original == null) {
        return null;
    }

    final boolean[][] result = new boolean[original.length][];
    for (int i = 0; i < original.length; i++) {
        result[i] = Arrays.copyOf(original[i], original[i].length);
        // For Java versions prior to Java 6 use the next:
        // System.arraycopy(original[i], 0, result[i], 0, original[i].length);
    }
    return result;
}


在Java 8中,可以使用lambdas作为单行代码实现:

1
2
3
< T > T[][] deepCopy(T[][] matrix) {
    return java.util.Arrays.stream(matrix).map(el -> el.clone()).toArray($ -> matrix.clone());
}


我是Arrays实用程序的粉丝。它具有copyOf方法,该方法将为您完成一维数组的深层复制,因此您需要以下内容:

1
2
3
4
//say you have boolean[][] foo;
boolean[][] nv = new boolean[foo.length][foo[0].length];
for (int i = 0; i < nv.length; i++)
     nv[i] = Arrays.copyOf(foo[i], foo[i].length);


我设法提出了一个递归数组深层副本。即使对于维度长度不同的多维数组,例如

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

这是实用程序方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
@SuppressWarnings("unchecked")
public static < T > 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);
}

编辑:更新了代码以使用基本数组。


是的,这是唯一的方法。 java.util.Arrays和commons-lang都不提供数组的深层副本。


这是一个使用java.lang.reflect.Array的反思性示例,它更健壮并且更易于理解。此方法将复制任何数组,并深度复制多维数组。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package mcve.util;

import java.lang.reflect.*;

public final class Tools {
    private Tools() {}
    /**
     * Returns a copy of the specified array object, deeply copying
     * multidimensional arrays. If the specified object is null, the
     * return value is null. Note: if the array object has an element
     * type which is a reference type that is not an array type, the
     * elements themselves are not deep copied. This method only copies
     * array objects.
     *
     * @param  array the array object to deep copy
     * @param  < T >   the type of the array to deep copy
     * @return a copy of the specified array object, deeply copying
     *         multidimensional arrays, or null if the object is null
     * @throws IllegalArgumentException if the specified object is not
     *                                  an array
     */

    public static < T > T deepArrayCopy(T array) {
        if (array == null)
            return null;

        Class< ? > arrayType = array.getClass();
        if (!arrayType.isArray())
            throw new IllegalArgumentException(arrayType.toString());

        int length = Array.getLength(array);
        Class< ? > componentType = arrayType.getComponentType();

        @SuppressWarnings("unchecked")
        T copy = (T) Array.newInstance(componentType, length);

        if (componentType.isArray()) {
            for (int i = 0; i < length; ++i)
                Array.set(copy, i, deepArrayCopy(Array.get(array, i)));
        } else {
            System.arraycopy(array, 0, copy, 0, length);
        }

        return copy;
    }
}

您可以遍历此数组并执行一系列Arrays.copyOf方法的调用:

1
2
3
4
5
6
7
8
9
10
11
boolean[][] arr1 = {{true, true}, {false, true}};    // original array
boolean[][] arr2 = Arrays.copyOf(arr1, arr1.length); // shallow copy
boolean[][] arr3 = Arrays.stream(arr1)               // deep copy
        .map(arr -> Arrays.copyOf(arr, arr.length))
        .toArray(boolean[][]::new);

arr1[0][0] = false;

System.out.println(Arrays.deepToString(arr1)); // [[false, true], [false, true]]
System.out.println(Arrays.deepToString(arr2)); // [[false, true], [false, true]]
System.out.println(Arrays.deepToString(arr3)); // [[true, true], [false, true]]

或者您可以调用Object.clone方法:

1
2
3
boolean[][] arr3 = Arrays.stream(arr1)
        .map(boolean[]::clone)
        .toArray(boolean[][]::new);

或者您可以为此创建通用方法:

1
2
3
4
5
static < T > T[][] deepCopy(T[][] matrix) {
    return Arrays.stream(matrix)
            .map(arr -> arr.clone())
            .toArray(s -> matrix.clone());
}

另请参阅:在2D数组的情况下,为什么Array.copyOf()会使原始数组变异?