java - 数组多重赋值的意外输出

标签 java arrays

<分区>

考虑

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/

相关文章:

java - list 文件从不保存我在制作 jar 文件时设置的内容

java - 使用堆栈的二叉搜索树的中序树遍历算法

java - 从计算机中的文件在java中播放.wav文件

c++ - 从每列具有不同数量值的文件中读取值,C++

python - numpy 如何排序数组切片索引?

java - 使用 Streams API 收集器平均 BigDecimals

java - NETSH 不产生输出

javascript - 在 JavaScript 中删除 forEach 内的 forEach

javascript - 使用lodash groupBy函数对数组中的对象进行分类

c# - 从数组中获取通用枚举器