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

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

Barbara Streisand
Barbara StreisandOriginal
2024-12-21 17:34:11719browse

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

Deep Copy of 2D Arrays in Java: A Comprehensive Guide

Using .clone() on a 2D array can lead to shallow copies, which may result in unexpected behavior. To perform a deep copy that creates a new independent copy of the original array, a more thorough approach is required.

Iterative Deep Copy with System.arraycopy

One approach to deep copying a 2D boolean array is to iterate through it and use System.arraycopy to copy each row into a new array. This involves creating a new 2D array and then iterating through the original array, copying each row element by element into the corresponding row in the new array.

Java 6 Option: java.util.Arrays#copyOf

If you're using Java 6 or later, you can simplify this process by utilizing the java.util.Arrays#copyOf methods. This class provides a convenient way to copy arrays.

Sample Code:

The following code sample demonstrates how to perform a deep copy of a 2D boolean array using the iterative approach:

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

By following these steps, you can effectively create deep copies of 2D boolean arrays in Java, ensuring that changes made to one array do not affect the other.

The above is the detailed content of How to Perform a Deep Copy of a 2D Array in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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