Copying a Two-Dimensional Array Effectively in Java
When working with two-dimensional arrays, it is often necessary to create a copy of the original array to preserve its original values. However, direct assignments such as old = current can lead to unintended consequences.
Understanding Java Array Assignment
In Java, arrays are objects, and assignments between arrays are references to the same underlying array. Therefore, updating one array affects the other because they both point to the same data.
Incorrect Copying Methods
The provided methods, old() and keepold(), simply assign references to the arrays. As a result, when current is updated after calling old(), the changes are also reflected in old. Similarly, after calling keepold(), current becomes a reference to old, and any updates to old update current.
Effective Copying with the Streams API (Java 8 )
To create a true copy of the array, it is necessary to perform a deep copy. The streams API introduced in Java 8 provides an efficient way to achieve this using the following code:
<code class="java">int[][] copy = Arrays.stream(matrix).map(int[]::clone).toArray(int[][]::new);</code>
Here, each row of the input array (matrix in this example) is cloned using map(int[]::clone), creating a new array for each row. The resulting stream of cloned arrays is then converted back to a two-dimensional array using toArray(int[][]::new). This process ensures that both copy and the original array are distinct and can be modified independently.
The above is the detailed content of How do you create a true copy of a two-dimensional array in Java without unintended consequences?. For more information, please follow other related articles on the PHP Chinese website!