是否“=”在数组中使用时表现得有些不同? [英] Does "=" behave somehow diffrent when used in arrays?

查看:65
本文介绍了是否“=”在数组中使用时表现得有些不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿,

i刚开始使用java,我正在玩数组,这是教程中的当前步骤。

我不明白为什么这样:

Hey,
i just started with java and i'm playing around with arrays wich are the current step in the tutorial.
What i dont understand is why this:

int a = 7;
int b = a;
b = a + 3;
System.out.println(a);



打印7,而这:


prints 7 while this:

int[] c = new int[1];
c[0] = 7;

int[] d;
d = c;
d[0] = c[0] + 3;
System.out.println(c[0]);



打印10.



希望这不是一个不言而喻的问题。


prints 10.

Hope this isn't a to self evident question to ask.

推荐答案

理解这一点的最好方法是通过调试器运行它并完全按照发生的情况进行操作。 br />
The best way to understand this is to run it through a debugger and follow exactly what happens.
int[] c = new int[1];
c[0] = 7;



这声明一个数组变量 c ,为它分配一个数组一个元素,并将值 7 放入单个元素中。


This declares an array variable c, assigns it an array of one element, and puts the value 7 into the single element.

int[] d;
d = c;



这声明了一个数组变量 d ,这个数组是 c 指向进入它。在这一点上,c和d都指的是相同的数据数组,就像我的车和我妻子的车都指的是同一辆车,因为我们之间只有一辆。


This declares an array variable d, cities the array that c "points at" into it. At this point, c and d both refer to the same array of data, in the same way as "my car" and "my wife's car" both refer to the same vehicle because we only have one between us.

d[0] = c[0] + 3;
System.out.println(c[0]);



因为它们都是同一个数组,所以你检索一个值,加3,然后放它回到了它的来源。继续汽车的比喻,如果我将钱包放在我的车的手套箱里,我的妻子可以打开她的车的手套箱,找到我的钱包,花掉我所有的钱!


So since they are both the same array, you retrieve a value, add 3, and put it back where it came from. To continue the car metaphor, if I put my wallet in the glove box of "my car", my wife can open the glove box of "her car", find my wallet, and spend all my money!


这篇关于是否“=”在数组中使用时表现得有些不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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