<分区>
考虑
int b = 2;
int[] a = new int[4];
a[a[b]] = a[b] = b = 2;
for (int i = 0; i <= 3; i++)
{
System.out.println(a[i]);
}
输出是
2
0
2
0
我原以为 a[0]
为零。
<分区>
考虑
int b = 2;
int[] a = new int[4];
a[a[b]] = a[b] = b = 2;
for (int i = 0; i <= 3; i++)
{
System.out.println(a[i]);
}
输出是
2
0
2
0
我原以为 a[0]
为零。
最佳答案
摘自 JLS 15.26.1。简单赋值运算符 =
If the left-hand operand is an array access expression (§15.13), possibly enclosed in one or more pairs of parentheses, then:
First, the array reference subexpression of the left-hand operand array access expression is evaluated. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason; the index subexpression (of the left-hand operand array access expression) and the right-hand operand are not evaluated and no assignment occurs.
这意味着 a[a[b]]
的计算结果为 a[0]
,因为它首先被计算。然后我们简单地按照 a[0] = a[b] = b = 2
进行,赋值从右到左进行。
参见 http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.26.1
关于java - 数组多重赋值的意外输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22632116/