java - 在同一语句中为数组分配多个值

标签 java arrays variable-assignment

我在下面有一个 java 代码片段:

int arr[] = new int[5];
int index = 0;
arr[index] = index = 3;

System.out.println("arr[0] = " + arr[0]);
System.out.println("arr[3] = " + arr[3]);

输出是:

arr[0] = 3
arr[3] = 0

第 3 行到底发生了什么?

最佳答案

Java 语言规范:

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 仍然是 0。现在 index = 3 被评估,并且 3 被存储在索引中。现在第一个赋值已准备好完成,因此 3 被赋值给元素零。

为了清晰起见,Java 语言设计者建议避免依赖此规则,确保表达式只有一个副作用。但是,您的表达式有两个副作用,其中一个依赖于另一个的完成。

It is recommended that code not rely crucially on this specification. Code is usually clearer when each expression contains at most one side effect, as its outermost operation, and when code does not depend on exactly which exception arises as a consequence of the left-to-right evaluation of expressions.

关于java - 在同一语句中为数组分配多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26690619/

相关文章:

java JNA - 查找部分窗口标题

java - 多线程和停止线程

node.js - 带 Sequelize 的加法和减法赋值运算符

java - 我需要一些帮助,用 java 读取 WAV 文件并确定其各种幅度

javascript - 如何从 php 变量数组执行 jquery 自动完成功能

Java:对象[]中的NullExceptionPointer

java - 无法将 String 转换为 int,但两者都是字符串?

java - 分配给Java中的字节数组

c - 字符串赋值的类型不完整

java - java.time 无法解析秒的小数部分吗?