Why does the Java increment operator allow narrowing operations without explicit cast?
本问题已经有最佳答案,请猛点这里访问。
Possible Duplicate:
Java += operator
在爪哇,这是无效的(没有编译),正如预期的那样:
1 2 3  | long lng = 0xffffffffffffL; int i; i = 5 + lng; //"error: possible loss of magnitude"  | 
但这很好(?!)
1 2 3  | long lng = 0xffffffffffffL; int i = 5; i += lng; //compiles just fine  | 
这显然是一个缩小的操作,可能会超过
这在JLS 15.26.2中定义:
A compound assignment expression of the form
E1 op= E2 is equivalent toE1 = (T) ((E1) op (E2)) , whereT is the type ofE1 , except thatE1 is evaluated only once.
换句话说,
1 2 3  | i+=lng;  is same as i = int(i+lng);  | 
来自JLS:
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.
根据JLS第15.26.2节,编译器不会抱怨。复合赋值运算符:
A compound assignment expression of the form
E1 op= E2 is equivalent toE1 = (T) ((E1) op (E2)) , whereT is the type ofE1 , except thatE1 is evaluated only once.
因此,
1  | i += lng;  | 
等于
1  | i = (int)(i + lng);  |