Creating Deep Copies of 2D Boolean Arrays in Java
Problem:
Avoid using .clone() when manipulating 2D boolean arrays, as it creates shallow copies instead of deep copies.
Question:
How to perform a deep copy of a 2D boolean array in Java?
Answer:
Iterate over the original array to create a new array with independent elements.
Java 6 Solution:
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); } return result; }
Pre Java 6 Solution:
// For Java versions prior to 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] = new boolean[original[i].length]; System.arraycopy(original[i], 0, result[i], 0, original[i].length); } return result; }
The above is the detailed content of How to Create a Deep Copy of a 2D Boolean Array in Java?. For more information, please follow other related articles on the PHP Chinese website!