I have a bunch of num开发者_如何转开发eric values. They can be Short
, Integer
, Long
, Float
or Double
(and are the output of an external library (snakeYaml) which returns these as type Object
)
I'd like to convert these Objects (which are guaranteed to be Numbers
) to Double
values in my program. (Storage space is not an issue).
The Java compiler obviously throws a ClassCastException
when attempting to cast from an object which is actually an Short
/Integer
/Long
/Float
to a Double
.
Any hints as to the most efficient method to adopt would be gratefully acknowledged.
They can be Short, Integer, Long, Float or Double
These classes are all subclasses of the Number
class, which means that you can always use the Number.doubleValue
method.
Example:
Number[] nums = { new Double(1.2), new Integer(5), new Float(3.0) };
double num1 = nums[0].doubleValue();
double num2 = nums[1].doubleValue();
double num3 = nums[2].doubleValue();
or, if you really want Double
values, you can rely on autoboxing and simply do:
Double num1 = nums[0].doubleValue();
Double num2 = nums[1].doubleValue();
Double num3 = nums[2].doubleValue();
Use Number.doubleValue() method to achieve that. With autoboxing you can assing its return value directly do Double
.
First, you need to cast to Double
instead of double
. But that only works for the Objects that are really Doubles and not Integer or Long or Float etc.
To get around that, cast to Number
and use doubleValue()
Object o = 10;
double i = ((Number)o).doubleValue();
ps. I'm unfamiliar with snakeYaml, but the api you describe is either designed completely wrong, or you are using it wrong. It makes no sense to return numbers as Objects. Would be interesting to see some example code of how you use it.
精彩评论