关于编译器错误:为什么Java增量运算符允许在没有显式转换的情况下缩小操作?

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

这显然是一个缩小的操作,可能会超过int的范围。那么为什么编译器不抱怨呢?


这在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.

换句话说,i += lng隐式执行强制转换。


i += lng;复合赋值运算符cast的隐式。

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 to E1 = (T) ((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once.

因此,

1
i += lng;

等于

1
i = (int)(i + lng);