为什么将 short 变量分配给 Integer 引用会产生编译时错误?
我在 Java 中有以下代码:
I have the following code in Java :
class Boxing
{
public static void main(String args[])
{
short s = 10;
Integer iRef = s;
}
}
为什么编译会报错?如果我在表达式中显式地将 short 类型转换为整数,它将成功编译.由于我在表达式中使用 short 类型不是默认情况下应该是整数而不需要显式大小写的类型吗?
Why does it produce an error in compilation? If I explicitly typecast the short to an integer in the expression, it compiles successfully. Since I'm using a short in an expression isn't the type of that supposed to be an integer by default without requiring the explicit case?
您希望这里发生两件事:加宽和自动装箱.
You want to have two things happening here: widening and auto-boxing.
不幸的是,Java 只会自动执行这两项中的一项.其原因很可能是自动装箱引入的很晚(在 Java5 中),他们必须小心不要破坏现有代码.
Unfortunately, Java does only one of the two automatically. The reason for that is most likely that autoboxing was introduced fairly late (in Java5), and they had to be careful to not break existing code.
你可以做到
int is = s; // widening
Short sRef = s; // autoboxing
Integer iRef = (int) s; // explicit widening, then autoboxing