8

由于复合赋值和递增/递减运算符中的隐式转换,以下编译:

byte b = 0;
++b; b++; --b; b--;
b += b -= b *= b /= b %= b;
b <<= b >>= b >>>= b;
b |= b &= b ^= b;

并且由于自动装箱和自动拆箱,以下内容也可以编译:

Integer ii = 0;
++ii; ii++; --ii; ii--;
ii += ii -= ii *= ii /= ii %= ii;
ii <<= ii >>= ii >>>= ii;
ii |= ii &= ii ^= ii;

然而,以下代码段中的最后一行给出了编译时错误:

Byte bb = 0;
++bb; bb++; --bb; bb--; // ... okay so far!
bb += bb; // DOESN'T COMPILE!!!
// "The operator += is undefined for the argument type(s) Byte, byte"

谁能帮我弄清楚这里发生了什么?该byte b版本编译得很好,所以不应该Byte bb效仿并根据需要进行适当的装箱和拆箱以适应吗?


额外的问题

那么有没有办法让复合赋值运算符与左侧的 , 和 一起使用,或者它们Byte对于Character这些类型来说只是非法的(!!!) ?Short

4

1 回答 1

6

该标准的第5.1.7 节(装箱)说:

From type boolean to type Boolean
From type byte to type Byte
From type char to type Character
From type short to type Short
From type int to type Integer
From type long to type Long
From type float to type Float
From type double to type Double

注意没有int to Byte。当你这样做时bb + bb,它会转换为 int + int,而不是装箱回Byte. 对于byte版本,直接转换int + intbyte(缩小原始转换,第 5.1.3 节),因此是允许的。

于 2010-04-24T13:31:03.963 回答