Home > Java > javaTutorial > How to Perform a Deep Copy of a 2D Boolean Array in Java?

How to Perform a Deep Copy of a 2D Boolean Array in Java?

Barbara Streisand
Release: 2024-12-19 02:55:10
Original
977 people have browsed it

How to Perform a Deep Copy of a 2D Boolean Array in Java?

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;
}
Copy after login

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;
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template