Deep Copying a 2D Array in Java
The java.lang.clone() method creates a shallow copy of an array, meaning that it only duplicates the reference to the original array. Modifying the copy will still affect the original array. A deep copy, on the other hand, creates a completely separate instance of the array, with its own set of elements.
Performing a Deep Copy
To perform a deep copy of a boolean[][] array, you can iterate over the array and create a new array for each row:
boolean[][] deepCopy(boolean[][] original) { if (original == null) { return null; } 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; }
For Java versions prior to Java 6, you can use System.arraycopy as shown below:
boolean[][] deepCopy(boolean[][] original) { if (original == null) { return null; } 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 Perform a Deep Copy of a 2D Boolean Array in Java?. For more information, please follow other related articles on the PHP Chinese website!