复合分配的自动(取消)装箱失败
由于复合赋值和递增/递减运算符中的隐式转换,以下代码可以编译:
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 一起使用,或者它们是对于这些类型来说根本不合法(!!!)?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
§ 5.1.7(拳击) 节标准的内容是:
注意没有
int to Byte
。当您执行bb + bb
时,它会转换为 int + int,而不会装回Byte
。对于byte
版本,int + int
直接转换回byte
(缩小原始转换,§ 5.1.3),因此这是允许的。Section § 5.1.7 (Boxing) of the standard says:
Note there is no
int to Byte
. When you dobb + bb
it's converted to int + int, which isn't boxed back toByte
. For thebyte
version,int + int
is cast back tobyte
directly (narrowing primitive conversions, § 5.1.3) so it's allowed.