Why unboxing doesn't work : Unresolved compilation error: Cannot cast from double to Long?

Why unboxing doesn't work : Unresolved compilation error: Cannot cast from double to Long?

据我了解,Java 会自动处理自动装箱和拆箱,即将基元转换为对象包装器,反之亦然。但是,拆箱在下面的代码中似乎不起作用。

public class TestMath {
    public static void main(String[] args) {
        Long resultLong = (Long) Math.pow(10, 10);
        System.out.println(resultLong);
    }
}

上面的代码给我编译错误,直到我通过将 (Long) 替换为 (long) 手动拆箱。我想了解这背后的原因。

编译错误如下图:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: Cannot cast from double to Long

Math.pow(10, 10) returns 一个 double,可以自动装箱成 Double,而不是 Long.

如果您将结果显式转换为 long,编译器可以将 long 自动装箱为 Long

至于为什么 (Long) Math.pow(10, 10) 不起作用 - JLS 中没有定义从 doubleLong 的转换。唯一支持的装箱转换是从基元到其对应的引用类型:

5.1.7. Boxing Conversion

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

你 misunderstood/confused 与 castingboxing/unboxing。两者是不同的概念。

 Math.pow(10, 10)

returns double 和 boxing/unboxing 发生在各自的基元和包装器之间(int <=> Integerlong <=> Long)。不适用于其他类型 (double <!=!> Long)。

由于您试图将 double 赋值给 long 值,编译器给出了错误。但是分配给 Double 作品。

Double resultLong =   Math.pow(10, 10);

在上面的行中,pow 方法实际上 returns 类型 double 并且将被转换为 Double 因为它们都是一对原始类型和包装器。