由于复合赋值和增量/减量运算符中的隐式强制转换,因此可以进行以下编译:
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
一起使用,或者对于这些类型,它们仅仅是非法的(!!!)吗? 最佳答案
标准的§ 5.1.7 (Boxing)部分说:
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 + int
直接转换回byte
(缩小原始转换§ 5.1.3),以便允许使用。