Java 数组 - 为什么输出是“1”? ?
为什么本例中的输出是1?
public static void main(String[] args){
int[] a = { 1, 2, 3, 4 };
int[] b = { 2, 3, 1, 0 };
System.out.println( a [ (a = b)[3] ] );
}
我认为会是2。即,表达式的计算结果为:
a[(a=b)[3]]
a[b[3]] //because a is now pointing to b
a[0]
因为 a 指向 b,所以 a[0] 不应该是 2 吗?
提前致谢。
Why is the output in this example 1?
public static void main(String[] args){
int[] a = { 1, 2, 3, 4 };
int[] b = { 2, 3, 1, 0 };
System.out.println( a [ (a = b)[3] ] );
}
I thought it would be 2. i.e., the expression is evaluated as:
a[(a=b)[3]]
a[b[3]] //because a is now pointing to b
a[0]
Shouldn't a[0] be 2 because a is pointing to b?
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
每个运算符的参数都是从左到右计算的。即,
[...]
前面的a
在其内容之前被评估,此时它仍然引用第一个数组。The arguments to each operator are evaluated left-to-right. I.e., the
a
in front of the[...]
is evaluated before its contents, at which point it still refers to the first array.这也让我很奇怪......但是,请检查第 15.7.1 节 此处
本质上,操作数是从左到右计算的。但还要注意这一点:
That weirded me out as well... however, check section 15.7.1 over here
Essentially, operands are evaluated from left to right. But also note this:
解释如下:
这里有一个技巧:
a
被评估为b
分配给它之前的值。考虑一下 Java 中的运算符优先级。应该更明显一点。
is interpreted as follows:
Here is the trick here:
a
is evaluated as the value beforeb
is assigned to it.Think about the operator precedence in Java. It should be a bit more obvious.
正如 Marcelo Cantos 先生所指出的,每个运算符的参数都是从左到右评估的。因此,我认为执行如下:
外部“a”将获取“1,2,3,4”,然后评估其参数 (a=b)[3]。因此现在 a=b 并且返回 b 数组中索引 3 处的元素,该元素也由 a 指向。
因此,我们从参数评估中得到“0”。如前所述,外部 a 仍然引用旧内容,因此给出 1,2,3,4 数组中的 a[0]。
因此我们得到“1”。
这是我的理解。如果有误请告诉我。
谢谢,
As Mr Marcelo Cantos Pointed out, Arguments to each operator are evaluated from left to right. Therefore here is what I think the execution is
Here the outer 'a' will fetch "1,2,3,4" and then its argument (a=b)[3] is evaluated. Thus now a=b and the element at index 3 in b array is returned which is also pointed by a.
Hence we get a '0' from the argument evaluation. As said previously, outer a still refers to old contents Thus gives a[0] in 1,2,3,4 array.
Therefore we get a '1'.
This is my understanding. Please let me know if its wrong.
Thanks,