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:
obj
is aNumber
and 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.