如何制作数组的副本而不是在Java中引用? [英] how to make copy of array instead of reference in java?

查看:94
本文介绍了如何制作数组的副本而不是在Java中引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将给定数组精确复制到其他数组,但是即使我更改了新数组中任何值,也不会更改原始数组中的值。
我尝试了以下代码,但在第三行之后,数组都发生了更改,并获得了相同的值。

I want to make an exact copy of given array to some other array but such that even though I change the value of any in the new array it does not change the value in the original array. I tried the following code but after the third line both the array changes and attains the same value.

int [][]a = new int[][]{{1,2},{3,4},{5,6}};
int[][] b = a;
b[1][0] = 7;

我也尝试过第二行

int[][] b = (int[][])a.clone();

int [][] b = new int [3][2];
System.arraycopy(a,0,b,0,a.length);

int [][] b = Arrays.copyOf(a,a.length);

这些都没有帮助。请给我建议一个合适的方法。我已经在Eclipse剪贴簿中测试过这段代码。

None of these helped. Please suggest me an appropriate method. I've tested this piece of code in eclipse scrapbook.

推荐答案

您必须复制数组的每一行;您无法复制整个阵列。您可能已经听说过这种称为深度复制的方法。

You have to copy each row of the array; you can't copy the array as a whole. You may have heard this called deep copying.

接受 $ 循环需要诚实至善的经历

Accept that you will need an honest-to-goodness for loop.

int[][] b = new int[3][];
for (int i = 0; i < 3; i++) {
  b[i] = Arrays.copyOf(a[i], a[i].length);
}

这篇关于如何制作数组的副本而不是在Java中引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆