Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
166 views
in Technique[技术] by (71.8m points)

java - Cast object (type double) to int

Okay, so if I have this code

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

Everything works fine, but

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

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

Though, when I do

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

or

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

Nothing's wrong again.

Why do you have to cast it to double first ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

When you're casting from Object, you're unboxing from the wrapper type... and you can only unbox to the original type, basically. It's effectively a cast to the relevant wrapper type, followed by a call to the appropriate xxxValue method. So this:

Object x = ...;
double d = (double) x;

is equivalent to:

Object x = ...;
double d = ((Double) x).doubleValue();

That cast to Double will obviously fail if x isn't a reference to a Double.

So your problematic code is equivalent to:

Object a = Double.valueOf(1.5); // Auto-boxing in the original code
int b = ((Integer) a).intValue(); // Unboxing in the original code
System.out.println(b);

Hopefully now it's obvious why that would fail - because the first line creates a Double which you're then trying to cast to Integer.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...