Java 基本数据类型数组
为什么接下来的代码会像使用引用类型而不是原始类型一样工作?
int[] a = new int[5];
int[] b = a;
a[0] = 1;
b[0] = 2;
a[1] = 1;
b[1] = 3;
System.out.println(a[0]);
System.out.println(b[0]);
System.out.println(a[1]);
System.out.println(b[1]);
输出是: 2 2 3 3 而不是 1 2 1 3
Why next code works like it uses reference types rather than primitive types?
int[] a = new int[5];
int[] b = a;
a[0] = 1;
b[0] = 2;
a[1] = 1;
b[1] = 3;
System.out.println(a[0]);
System.out.println(b[0]);
System.out.println(a[1]);
System.out.println(b[1]);
And the output is:
2
2
3
3
rather than
1
2
1
3
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
int 数组的内容可能不是引用,但 int[] 变量是。通过设置 b = a,您将复制引用,并且两个数组指向同一块内存。
The contents of the int array may not be references, but the int[] variables are. By setting
b = a
you're copying the reference and the two arrays are pointing to the same chunk of memory.我描述了您在这里所做的事情:
int[] a = new int[5];
int[] b = a;
的引用>I describe what you are doing here:
int[] a = new int[5];
int[] b = a;
不会通过
int[] b = a
创建新实例,如果您需要新实例(以及您的预期结果),则 添加
clone()
:int[] b = a.clone()
祝你好运
you are not creating a new instance by
int[] b = a
if you need new instance (and your expected result) add
clone()
:int[] b = a.clone()
good luck
a
和b
都指向(is)同一个数组。更改a
或b
中的值将会更改另一个的相同值。Both
a
andb
points to (is) the same array. Changing a value in eithera
orb
will change the same value for the other.