Home >Java >javaTutorial >How to Efficiently and Safely Copy a 2D Array in Java?

How to Efficiently and Safely Copy a 2D Array in Java?

DDD
DDDOriginal
2024-11-01 12:42:02387browse

How to Efficiently and Safely Copy a 2D Array in Java?

How to Copy a 2D Array in Java

Question:

You have a 2D array called matrix that you want to copy into a local variable in a method for editing. What's the most efficient and error-proof way to create a complete copy?

Answer:

There are two recommended ways to copy a 2D array in Java:

Using clone():

The clone() method creates a new array with the same size and contents as the original. For 2D arrays, you need to clone each individual row:

<code class="java">int[][] myInt = new int[matrix.length][];
for (int i = 0; i < matrix.length; i++)
    myInt[i] = matrix[i].clone();</code>

Using System.arraycopy():

The System.arraycopy() method can also be used to copy a 2D array. It requires creating a new array and manually copying each element:

<code class="java">int[][] myInt = new int[matrix.length][];
for (int i = 0; i < matrix.length; i++) {
  int[] aMatrix = matrix[i];
  int aLength = aMatrix.length;
  myInt[i] = new int[aLength];
  System.arraycopy(aMatrix, 0, myInt[i], 0, aLength);
}</code>

Advantages:

Both methods are faster and less prone to errors than manually copying the array. System.arraycopy() is particularly efficient because it is implemented in native code.

Note:

In some cases, you may only need a shallow copy of the array, where the modified elements in the copy are reflected in the original array. For a shallow copy, you can simply assign the array directly, e.g., int[][] myInt = matrix;. However, this is not recommended for editing purposes.

The above is the detailed content of How to Efficiently and Safely Copy 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