【问题标题】:Auto-(un)boxing fail for compound assignment复合分配的自动(取消)装箱失败
【发布时间】:2011-02-11 20:52:42
【问题描述】:

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

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;

然而,以下 sn-p 的最后一行给出了编译时错误:

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 不应该效仿并根据需要进行适当的装箱和拆箱以适应吗?


补充问题

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

【问题讨论】:

    标签: java compiler-errors autoboxing implicit-conversion compound-assignment


    【解决方案1】:

    标准的§ 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),因此是允许的。

    【讨论】:

    • 我认为既然有intbyte,还有byteByte,编译器会找出从int 到@987654335 的有效路径@ 毕竟!显然情况并非如此?有没有办法让复合赋值与显式转换一起工作?
    • 很明显这会起作用bb = Byte.valueOf((byte)(bb + bb)),但除此之外我不知道。
    猜你喜欢
    • 2013-12-25
    • 2011-10-11
    • 2018-02-21
    • 1970-01-01
    • 1970-01-01
    • 2017-05-08
    • 1970-01-01
    • 2012-03-19
    • 2016-01-21
    相关资源
    最近更新 更多