Jak zrobić głęboką kopię tablicy 2d w Javie?

Właśnie zostałem ugryziony przez użycie .clone() Na mojej tablicy 2d boolean, myśląc, że to głęboka Kopia.

Jak mogę wykonać głęboką kopię tablicy boolean[][]?

Czy mam zrobić pętlę i zrobić serię System.arraycopy's?

Author: Radiodef, 2009-10-14

6 answers

Tak, powinieneś iterować ponad 2D tablicą boolean, aby ją głęboko skopiować. Spójrz również na metody java.util.Arrays#copyOf, Jeśli korzystasz z Java 6.

Proponuję kolejny kod do Javy 6:

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;
}
 49
Author: Rorick,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-10-14 07:58:41

Jestem fanem narzędzia Arrays. Ma metodę copyOf, która zrobi dla Ciebie głęboką kopię tablicy 1-D, więc chcesz coś takiego:

//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);
 8
Author: perimosocordiae,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-10-14 07:52:58

Udało mi się stworzyć rekurencyjną kopię głębokiej tablicy. Wydaje się, że działa całkiem dobrze nawet dla wielowymiarowych tablic o różnych długościach wymiarów, np.

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

Oto metoda użytkowa.

@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);
}

Edit: Zaktualizowano kod do pracy z prymitywnymi tablicami.

 8
Author: Karl Bennett,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-04-28 17:14:07

Tak, to jedyny sposób. Ani java.util.Arrays ani commons-lang nie oferują głębokiej kopii dla tablic.

 6
Author: Aaron Digulla,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-10-14 07:51:34

W Javie 8 można to osiągnąć w postaci jednowersowej za pomocą lambda:

<T> T[][] deepCopy(T[][] matrix) {
    return java.util.Arrays.stream(matrix).map(el -> el.clone()).toArray($ -> matrix.clone());
}
 6
Author: SlavaSt,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-07-26 12:49:26

Oto refleksyjny przykład użycia java.lang.reflect.Array który jest bardziej wytrzymały i nieco łatwiejszy do naśladowania. Ta metoda kopiuje dowolną tablicę i głęboko kopiuje tablice wielowymiarowe.

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;
    }
}
 0
Author: Radiodef,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-29 22:56:53