Java:+=等价

标签 java variable-assignment compound-operator

是:

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/

相关文章:

java - URL 中的 % 重定向到 HTTP ERROR 400 而不是默认错误页面

java - 在 Java 中分配迭代器返回值的高性能影响?

Python:多重分配与个人分配速度

python - 写值需要多行时如何给变量赋值(python)

C - 逻辑复合运算符

java - 为什么我的线程在不同时间执行相同数量的工作?

java - Java 中的泛型工厂

java - 如何找到包含类定义的jar文件?

python - 在 python 中将 print() 与复合运算符一起使用

java - 为什么 i+=l 会编译,其中 i 是 int 而 l 是 long?