I have an Object obj that I know is actually a long.
In some Math code I need it as double.
Is it safe to directly cast it to double?
double x = (double)obj;
Or should I rather cast it first to long and then to double.
double x = (double)(long)obj;
I also found another (less readable) alternative:
double x = new Long((long)obj).doubleValue();
What are the dangers/implications of doing either?
Solution Summary:
objis aNumberand not along.- Java 6 requires explicit casting, e.g.:
double x = ((Number)obj).doubleValue() - Java 7 has working cast magic:
double x = (long)obj
For more details on the Java6/7 issue also read discussion of TJ’s answer.
Edit: I did some quick tests. Both ways of casting (explicit/magic) have the same performance.
As every primitive number in Java gets cast to its boxing type when an object is needed (in our case
Long) and every boxed number is an instance ofNumberthe safest way for doing so is:The danger here is, as always, that the
Objectwe want to cast is not of typeNumberin which case you will get aClassCastException. You may check the type of the object likeif you like to prevent class cast exceptions and instead supply a default value like
0.0. Also silently failing methods are not always a good idea.