是:
x -= y;
相当于:
x = x - y;
最佳答案
不,它们并不等同于您表达它们的方式。
short x = 0, y = 0;
x -= y; // This compiles fine!
x = x - y; // This doesn't compile!!!
// "Type mismatch: cannot convert from int to short"
第三行的问题是 -
执行 short
的所谓“数字提升”( JLS 5.6 )操作数,结果为 int
值,不能简单地分配给 short
没有 Actor 。 复合赋值运算符包含一个隐藏的转换!
确切的等效项在 JLS 15.26.2 Compound Assignment Operators 中列出。 :
A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T)((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once.
所以澄清一些微妙之处:
- 复合赋值表达式不会重新排序操作数
- 左边留在左边,右边留在右边
- 两个操作数都用括号括起来,以确保 op 具有最低的优先级
-
int x = 5; x *= 2 + 1; // x == 15, not 11
-
- 有一个隐藏的类型转换
-
int i = 0; i += 3.14159; // this compiles fine!
-
- 左边只计算一次
-
arr[i++] += 5; // this only increments i once
-
Java 还有*=
, /=
, %=
, +=
, -=
, <<=
, >>=
, >>>=
, &=
, ^=
和 |=
.最后 3 个也是为 boolean 值定义的 ( JLS 15.22.2 Boolean Logical Operators )。
相关问题
关于Java:+=等价,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2414531/