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

查看:130
本文介绍了将对象(类型为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 ?

推荐答案

当你申报时对象对象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 如果你尝试这样做。它不能直接从 Double 转到 Integer

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天全站免登陆