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 a Number
and not a long
.
- 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 of Number
the safest way for doing so is:
final Object object = 0xdeadbeefL;
final double d = ((Number)object).doubleValue();
The danger here is, as always, that the Object
we want to cast is not of type Number
in which case you will get a ClassCastException
. You may check the type of the object like
if(object instanceof Number) ...
if 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.
I have an Object obj
that I know is actually a long
.
No, you don't. long
is a primitive data type, and primitive types in Java are not objects. Note that there's a difference between the primitive type long
and java.lang.Long
, which is a wrapper class.
You cannot cast a Long
(object) to a long
(primitive). To get the long
value out of a Long
, call longValue()
on it:
Long obj = ...;
long value = obj.longValue();
Is it safe to directly cast it to double
?
If it's actually a primitive long
, then yes, you can cast that to a double
. If it's a Long
object, you don't need to cast, you can just call doubleValue()
on it:
double x = obj.doubleValue();
Simple casting should work perfectly fine. This will be faster than going via the wrapper classes, getting string representation and then parsing to double, create new instance again using the long value - and more importantly, it's more readable.
double d = (double)15234451L;
You can cast it to a Long
(since the Object
is not a long
but a Long
), and then cast the Long
to a double
:
double d = (double)(Long)obj;
For instance, this has the expected output of 2.6666666666666665:
public class CastDouble {
public static final void main(String[] args) {
Object o = 15L;
System.out.println(40 / (double)(Long)o);
}
}
You only need one cast, from Object to Long or long (which implicitly casts to Long then applies unboxing):
Object o = 5L;
double d = (long) o; //Apparently only works on Java 7+
//or
double d = (Long) o;