public class Conversions {
public static void main(String[] args) {
int index = 3;
int[] arr = new int[] { 10, 20, 30, 40};
arr[index] = index = 2; //(1)
System.out.println("" + arr[3] + " " + arr[2]);
}
}
我有这个,它给出了:
2 30
我希望它能给
40 2
在(1)为什么assignment中索引的值没有改成2(一直保持为3)。 ?
最佳答案
right-associativity section 15.26 隐含的 =
Java 语言规范 (JLS) 意味着您的表达式可以表示为 tree ,因此:
=
+------+-------+
| |
arr[index] =
+----+----+
| |
index 2
但是,section 15.7状态:
The Java programming language guarantees that the operands of operators appear to be evaluated in a specific evaluation order, namely, from left to right.
因此,arr[index]
的计算之前 index = 2
是,即 之前 的值index
已更新。
显然,您永远不应该编写依赖于这一事实的代码,因为它依赖于几乎没有读者理解的规则。
关于java - Java中的赋值运算符解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17778113/