复合分配的自动(非)装箱失败 [英] Auto-(un)boxing fail for compound assignment
问题描述
由于复合赋值和递增/递减运算符中的隐式转换,以下编译:
byte b = 0;
++ b; b ++; -b; b--;
b + = b - = b * = b / = b%= b;
b<< = b>> = b>>> = b;
b | = b& = b ^ = b;
由于自动装箱和自动取消装箱,以下还编译:
整数ii = 0;
++ ii; ii ++; --ii; ii--;
ii + = ii - = ii * = ii / = ii%= ii;
ii<< = ii>> = ii>>> = ii;
ii | = ii& = ii ^ = ii;
然而,下面代码段中的最后一行给出了编译时错误:
字节bb = 0;
++ bb; bb ++; --bb; bb--; // ...好吧,到目前为止!
bb + = bb; //不能编译!
//运算符+ =未定义参数类型字节,字节
谁能帮我找出这里发生了什么? byte b
版本编译很好,所以不应该 Byte bb
只是跟随,做适当的拳击和拆箱额外的问题
因此,有一种方法使复合赋值运算符与 Byte
, Character
和
第第5.1.7节(Boxing)的标准说:
从类型布尔到类型布尔
从类型字节类型字节
从类型char到类型字符
从类型short到类型short
从类型int到类型Integer
从类型long到类型Long
从类型float类型Float
从类型double到类型Double
注意没有 int to Byte
。当你做 bb + bb
时,它被转换为int + int,不会回到 Byte
。对于 byte
版本, int + int
将回复到 byte
(缩小原始转换,第5.1.3节),因此允许。
Thanks to the implicit casting in compound assignments and increment/decrement operators, the following compiles:
byte b = 0;
++b; b++; --b; b--;
b += b -= b *= b /= b %= b;
b <<= b >>= b >>>= b;
b |= b &= b ^= b;
And thanks to auto-boxing and auto-unboxing, the following also compiles:
Integer ii = 0;
++ii; ii++; --ii; ii--;
ii += ii -= ii *= ii /= ii %= ii;
ii <<= ii >>= ii >>>= ii;
ii |= ii &= ii ^= ii;
And yet, the last line in the following snippet gives compile-time error:
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"
Can anyone help me figure out what's going on here? The byte b
version compiles just fine, so shouldn't Byte bb
just follow suit and do the appropriate boxing and unboxing as necessary to accommodate?
Extra question
So is there a way to make compound assignment operators work with Byte
, Character
, and Short
on the left hand side, or are they simply illegal(!!!) for these types?
Section § 5.1.7 (Boxing) of the standard says:
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
Note there is no int to Byte
. When you do bb + bb
it's converted to int + int, which isn't boxed back to Byte
. For the byte
version, int + int
is cast back to byte
directly (narrowing primitive conversions, § 5.1.3) so it's allowed.
这篇关于复合分配的自动(非)装箱失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!