int[] arr = {1, 2, 3, 4, 5};
int[] copy = arr;
copy[4] = 2;
System.out.println(arr[4]);
所以它打印出2,但我不知道为什么当arr不等于拷贝时,它会这样做。不是应该是5岁还是我傻吗?
发布于 2020-03-29 23:32:40
,所以它打印出2,但我不知道为什么它会这样做,而arr并不等于复制。不是应该是5点吗?
不,这是预期的行为。这是因为copy
和arr
引用的是同一个数组对象。
以不可变的方式创建副本,如下所示:
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] arr = { 1, 2, 3, 4, 5 };
int[] copy = Arrays.copyOf(arr, arr.length);
copy[4] = 2;
System.out.println(arr[4]);
System.out.println(copy[4]);
int[] anotherCopy = arr.clone();
anotherCopy[4] = 2;
System.out.println(arr[4]);
System.out.println(anotherCopy[4]);
}
}
输出:
5
2
5
2
发布于 2020-03-29 23:33:57
编译器不是单独创建一个数组,而是为原始数组分配一个指针。换句话说,这两个数组实际上都是相同的数据,但名称和指针不同。改变一种会影响另一种。
https://stackoverflow.com/questions/60922048
复制相似问题