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

Viewed 90187

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 boolean[][] array?

Should I loop through it and do a series of System.arraycopy's?

7 Answers

You can iterate over this array and perform a series of calls of Arrays.copyOf method:

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]]

Or you can call Object.clone method:

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

Or you can create a generic method for this purpose:

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

See also: Why does Array.copyOf() mutate the original array in case of 2D Arrays?

Here's a reflective example using java.lang.reflect.Array which is more robust and a bit easier to follow. This method will copy any array, and deeply copies multidimensional arrays.

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;
    }
}
Related