为什么将短变量赋值给 Integer 引用会产生编译时错误?

Why does the assignment of a short variable to an Integer reference produce a compile time error?

我在 Java 中有以下代码:

class Boxing
    {
        public static void main(String args[])
        {
            short s = 10;
            Integer iRef = s;
        }
    }

为什么会编译出错?如果我在表达式中将 short 显式转换为整数,它会成功编译。因为我在表达式中使用了一个 short 类型,所以在不需要显式大小写的情况下,默认情况下它不是应该是整数的类型吗?

装箱转换将原始类型的表达式转换为相应的引用类型的表达式。具体来说,以下九种转换称为装箱转换:

From type boolean to type Boolean

From type byte to type Byte

From type short to type Short

From type char to type Character

From type int to type Integer

From type long to type Long

From type float to type Float

From type double to type Double

From the null type to the null type

参考:Conversions and Promotions Reference

您想在此处进行两件事:加宽和自动装箱。

不幸的是,Java 只会自动执行两者之一。原因很可能是自动装箱引入的时间很晚(在 Java5 中),他们必须小心不要破坏现有代码。

你可以做到

int is = s;    // widening

Short sRef = s;   // autoboxing

Integer iRef = (int) s;  // explicit widening, then autoboxing

这是来自 JLS 5.1.7

的文档

Boxing conversion converts expressions of primitive type to corresponding expressions of reference type. Specifically, the following nine conversions are called the boxing conversions:

From type boolean to type Boolean

From type byte to type Byte

From type short to type Short

From type char to type Character

From type int to type Integer

From type long to type Long

From type float to type Float

From type double to type Double

From the null type to the null type

基本上从shortInteger的直接转换不是Java的自动装箱过程的一部分。

如上所述,自动装箱只能将表示原始类型隐式转换为它表示包装器 class。由于不是这种情况,因此会导致编译时错误。

在考虑的代码中。

class Boxing
{
    public static void main(String args[])
    {
        short s = 10;
        Integer iRef = s;
    }
}

整数扩展 java.lang.Number。 java.lang.Short 也扩展了 java.lang.Number。但是 Short 和 Integer 没有直接关系,如果你想你可以 运行 下面的程序。

class Boxing
{
    public static void main(String args[])
    {
        short s = 10;
        Number iRef = s;
    }
}

它会 运行 而不会产生任何错误。

Java 尝试执行自动加宽,然后自动装箱,然后自动向上转换,但不会为同一分配执行其中两个。对于方法参数分配的相关案例,这已进行解释和图示here