将对象(double 类型)转换为 int [英] Cast object (type double) to int

查看:23
本文介绍了将对象(double 类型)转换为 int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,如果我有这个代码

Okay, so if I have this code

double a=1.5;
int b=(int)a;
System.out.println(b);

一切正常,但是

Object a=1.5;
int b=(int)a;
System.out.println(b);

运行后出现以下错误(Eclipse 没有出现任何错误)

gives the following error after running (Eclipse doesn't give any error)

java.lang.ClassCastException: java.lang.Double cannot be cast to java.lang.Integer

不过,当我这样做时

Object a=1.5;
double b=(double)a;
int c=(int)b;
System.out.println(c);

Object a=1.5;
int b=(int)(double)a;
System.out.println(b);

又出事了.

为什么要先将它转换为 double ?

Why do you have to cast it to double first ?

推荐答案

当你声明对象 Object a = 1.5 你可以通过检查 System.out.println(a.getClass()) 对象实际上被转换为 Double 实例.由于拆箱约定,这可以再次转换为 double.之后,可以将 double 值转换为 int.

When you declare the object Object a = 1.5 you can tell by checking System.out.println(a.getClass()) that the object is in fact cast to a Double instance. This can again be cast to a double because of unboxing conventions. After that the double value can be cast to an int.

然而,没有将 Double 实例转换为 int 的拆箱约定,因此如果您尝试这样做,运行时将发出 ClassCastException.它不能直接从 DoubleInteger.

There are however no unboxing conventions to cast from a Double instance to an int, so the runtime will issue an ClassCastException if you try and do that. It cannot directly go from Double to Integer.

这篇关于将对象(double 类型)转换为 int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆