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

user189661 picture user189661 · Oct 14, 2009 · Viewed 67.6k times · Source

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?

Answer

Rorick picture Rorick · Oct 14, 2009

Yes, you should iterate over 2D boolean array in order to deep copy it. Also look at java.util.Arrays#copyOf methods if you are on Java 6.

I would suggest the next code for Java 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;
}