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

前端 未结 6 1291
深忆病人
深忆病人 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:44

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

提交回复
热议问题