Home > Java > javaTutorial > body text

How do you create a true copy of a two-dimensional array in Java without unintended consequences?

Barbara Streisand
Release: 2024-10-30 19:27:02
Original
1001 people have browsed it

How do you create a true copy of a two-dimensional array in Java without unintended consequences?

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

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!