ClassCastException整数为双精度

问题描述 投票:3回答:5

为什么此代码引发此异常:

public class DS3{
    public static void main(String[] args) {
        double r = (double)((Object)4);
        System.out.println(r);          
    }   
}

线程“主”中的异常java.lang.ClassCastException:java.lang.Integer无法转换为java.lang.Double

而且,运行正常:

public class DS4{
        public static void main(String[] args) {
            double r = (double)(4);
            System.out.println(r);          
        }   
    }

都是试图将整数转换为双精度,对吗?

java classcastexception
5个回答
7
投票

都是试图将整数转换为双精度,对吗?

是,不是。>>

此行

double r = (double)((Object)4);

使编译器将4装在Integer中,并且Integer不能转换为双精度。

此代码段的字节码:

(double)((Object) 4)

如下所示:

// ...
5: iconst_4
6: invokestatic  #2    // Method Integer.valueOf
9: checkcast     #3    // class java/lang/Double
// ...

((第6行导致装箱,第9行引发异常。)

换句话说,相当于

Object tmp = (Object) 4;  // Auto-boxing to Integer
double d = (double) tmp;  // Illegal cast from Integer to double.

另一方面

double r = (double)(4);

4被认为是普通的int,将其[[can

强制转换为double

3
投票
您显示的两次转化,即

1
投票
在您的第一个示例中,4被自动装箱到Integer,然后无法将其强制转换为原始double

1
投票
第一次尝试将4转换为类型为Integer的对象,该对象基本上是保存int值为4的容器。

1
投票
您的问题与装箱和拆箱有关。您可以在这里阅读更多有关此信息:https://docs.oracle.com/javase/tutorial/java/data/autoboxing.html
© www.soinside.com 2019 - 2024. All rights reserved.