Re: How to cast an Object to Double?
www wrote:
I cannot figure out how to do it well. I have an Object, which is
retrieved from a map. It actually is a number(double). I need to get its
value.
double value = Double.parse((String)theObj); //this works
But:
double value = (Double)theObj; //this does not work in Eclipse, why?
It's not Eclipse that decides if this works, it's Java.
Is that because Double is subclass of Object, similarly a Animal can not
be casted into a Cat?
No.
So, I have to cast the Object to String first, then get the double
value? (String is a subclass of Object(?).
No.
Why the Object can be casted [sic] into String?)
Because all Objects have a toString() method. Beware, it might not do what
you expect.
This would be easier if you provided an SSCCE
<http://www.physci.org/codes/sscce.html>
but I'll do my best without one.
Assume a Map declared as
Map <String, Double> stuff = new HashMap <String, Double> ();
Later some code does:
Double d = stuff.get( key );
where key is some String. No casting needed.
If for some reason you were to use
Object o = stuff.get( key );
then you need to cast the return value, but that should work since you know
the map values are Double.
The only way I can imagine you getting the result you state, absent an SSCCE,
is that you used a raw Map type and inserted a non-Double into the value.
Provide an SSCCE and we'll see how close my guesses came.
--
Lew