一维数组
使用Arrays.copyOf()
int[] one = {1, 2, 3, 4, 5};
int[] one_copy = Arrays.copyOf(one, 5);
one[1] = 999;
System.out.println(Arrays.toString(one));
System.out.println(Arrays.toString(one_copy));
one_copy[2] = 999;
System.out.println(Arrays.toString(one));
System.out.println(Arrays.toString(one_copy));
运行结果
[1, 999, 3, 4, 5]
[1, 2, 3, 4, 5]
[1, 999, 3, 4, 5]
[1, 2, 999, 4, 5]
可以看到,对于一维数组,无论修改原数组,还是修改复制后的数组,都不会互相影响。
System.arraycopy()
int[] one = {1, 2, 3, 4, 5};
int[] one_copy = new int[5];
System.arraycopy(one, 0, one_copy, 0, 5);
one[1] = 999;
System.out.println(Arrays.toString(one));
System.out.println(Arrays.toString(one_copy));
one_copy[2] = 999;
System.out.println(Arrays.toString(one));
System.out.println(Arrays.toString(one_copy));
运行结果
[1, 999, 3, 4, 5]
[1, 2, 3, 4, 5]
[1, 999, 3, 4, 5]
[1, 2, 999, 4, 5]
同样,对于一维数组,无论修改原数组,还是修改复制后的数组,都不会互相影响。
二维数组
int[][] two = {{1, 2, 3}, {4, 5, 6}};
// int[][] two_copy = new int[2][3];
// System.arraycopy(two, 0, two_copy, 0, 2);
int[][] two_copy = Arrays.copyOf(two, 2);
two[0][1] = 999;
System.out.println(Arrays.deepToString(two));
System.out.println(Arrays.deepToString(two_copy));
two_copy[1][2] = 999;
System.out.println(Arrays.deepToString(two));
System.out.println(Arrays.deepToString(two_copy));
运行结果
[[1, 999, 3], [4, 5, 6]]
[[1, 999, 3], [4, 5, 6]]
[[1, 999, 3], [4, 5, 999]]
[[1, 999, 3], [4, 5, 999]]
可以看到,修改原数组后新数组也会被修改,修改新数组原数组也会被修改。
原因是对第二维每个数组的复制是浅复制。
正确的深复制方法是,遍历第一维,对第二维使用System.arraycopy()或Arrays.copyOf()
int[][] two = {{1, 2, 3}, {4, 5, 6}};
int[][] two_copy = new int[2][3];
for (int i = 0; i < two_copy.length; i++) {
// two_copy[i] = Arrays.copyOf(two[i], 3);
System.arraycopy(two[i], 0, two_copy[i], 0, 3);
}
two[0][1] = 999;
System.out.println(Arrays.deepToString(two));
System.out.println(Arrays.deepToString(two_copy));
two_copy[1][2] = 999;
System.out.println(Arrays.deepToString(two));
System.out.println(Arrays.deepToString(two_copy));
运行结果如下
[[1, 999, 3], [4, 5, 6]]
[[1, 2, 3], [4, 5, 6]]
[[1, 999, 3], [4, 5, 6]]
[[1, 2, 3], [4, 5, 999]]
这样对两个二维数组的改动不会互相影响。