简体   繁体   English

Java:+ =等价

[英]Java: += equivalence

Is: 方法是:

x -= y;

equivalent to: 相当于:

x = x - y;

No, they are NOT equivalent the way you expressed them. 不,它们与你表达它们的方式不相同。

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"

The problem with the third line is that - performs what is called "numeric promotion" ( JLS 5.6 ) of the short operands, and results in an int value, which cannot simply be assigned to a short without a cast. 第三行的问题是-执行short操作数的所谓“数字提升”( JLS 5.6 ),并产生一个int值,不能简单地将其赋值给没有强制转换的short Compound assignment operators contain a hidden cast! 复合赋值运算符包含隐藏的强制转换

The exact equivalence is laid out in JLS 15.26.2 Compound Assignment Operators : 确切的等价在JLS 15.26.2化合物分配操作符中列出

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. 形式E1 op = E2的复合赋值表达式等效于E1 =(T)((E1)op(E2)) ,其中TE1的类型,除了E1仅被评估一次。

So to clarify some of the subtleties: 所以澄清一些细微之处:

  • Compound assignment expression doesn't reorder the operands 复合赋值表达式不对操作数重新排序
    • Left hand side stays on the left, right hand side stays on the right 左侧停留在左侧,右侧停留在右侧
  • Both operands are fully-parenthesized to ensure op has the lowest precedence 两个操作数都是完全括号的,以确保op具有最低优先级
    • int x = 5; x *= 2 + 1; // x == 15, not 11
  • There is a hidden cast 有一个隐藏的演员
    • int i = 0; i += 3.14159; // this compiles fine!
  • The left hand side is only evaluated once 左侧仅评估一次
    • arr[i++] += 5; // this only increments i once

Java also has *= , /= , %= , += , -= , <<= , >>= , >>>= , &= , ^= and |= . Java还有*=/=%=+=-=<<=>>=>>>=&=^=|= The last 3 are also defined for booleans ( JLS 15.22.2 Boolean Logical Operators ). 最后3个也是为布尔值定义的( JLS 15.22.2布尔逻辑运算符 )。

Related questions 相关问题

Yes, it is. 是的。 This syntax is the same in most C-derived languages. 在大多数C派生语言中,此语法是相同的。

Not exactly. 不完全是。 The reason it was introduced in C was to allow the programmer to do some optimizations the compiler couldn't. 它在C中引入的原因是允许程序员做一些编译器无法做到的优化。 For example: 例如:

A[i] += 4

used to be compiled much better than 曾经比编译好得多

A[i] = A[i] + 4

by the compilers of the time. 由当时的编译器。

And, if "x" has side effects, eg "x++" then it is wildly different. 而且,如果“x”有副作用,例如“x ++”那么它就会大不相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM