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

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

Patricia Arquette
Release: 2024-12-22 01:29:22
Original
590 people have browsed it

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

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

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

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!

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