Java: many ways of casting a (long) Object to double

别说谁变了你拦得住时间么 提交于 2019-12-05 01:17:54

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;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!