Java:为什么(int) += (double)不会导致“不兼容类型”错误?(复制)

时间:2021-01-13 16:27:30

This question already has an answer here:

这个问题已经有了答案:

Here's an oddity:

这是一个奇怪的地方:

float a = 0;
a = a + Math.PI; // ERROR

and yet:

然而,:

a += Math.PI; // OK!

even this works:

即使是如此:

int b = 0;
b += Math.PI; // OK, too!

Why does the += operator allow lossy implicit type conversions?

为什么+=运算符允许有损隐式类型转换?

2 个解决方案

#1


16  

From JLS §15.26.2:

从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)),其中T是E1的类型,除了E1只计算一次。

Notice that there is a cast involved with the compound assignment. However, with the simple addition there is no cast, hence the error.

注意,复合赋值涉及一个cast。但是,使用简单的加法时不存在强制转换,因此会出现错误。

If we include the cast, the error is averted:

如果我们包括演员,错误被避免:

float a = 0;
a = (float) (a + Math.PI);  // works

It's a common misconception that x += y is identical to x = x + y.

一个常见的误解是,x += y与x = x + y是相同的。

#2


2  

That's because

这是因为

float a = 0;
double b = 1;
a += b;

is the equivalent of

相当于

float a = 0;
double b = 1;
a = (float)(a + b);

a += is the same as a = (<type of a>)(a +

a +=与a =( <类型为> )(a +)相同

#1


16  

From JLS §15.26.2:

从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)),其中T是E1的类型,除了E1只计算一次。

Notice that there is a cast involved with the compound assignment. However, with the simple addition there is no cast, hence the error.

注意,复合赋值涉及一个cast。但是,使用简单的加法时不存在强制转换,因此会出现错误。

If we include the cast, the error is averted:

如果我们包括演员,错误被避免:

float a = 0;
a = (float) (a + Math.PI);  // works

It's a common misconception that x += y is identical to x = x + y.

一个常见的误解是,x += y与x = x + y是相同的。

#2


2  

That's because

这是因为

float a = 0;
double b = 1;
a += b;

is the equivalent of

相当于

float a = 0;
double b = 1;
a = (float)(a + b);

a += is the same as a = (<type of a>)(a +

a +=与a =( <类型为> )(a +)相同