Java:许多方法将一个(长)对象转换为双重 [英] Java: many ways of casting a (long) Object to double

查看:154
本文介绍了Java:许多方法将一个(长)对象转换为双重的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Object obj ,我知道其实是一个 long
在某些数学代码中,我需要它作为 double

I have an Object obj that I know is actually a long. In some Math code I need it as double.

直接将其转换为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?

解决方案摘要


  • obj 是一个号码而不是 long

  • Java 6需要明确的转换,例如: double x =((Number)obj).doubleValue()

  • Java 7具有工作转换魔法: double x =(long)obj

  • 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

有关Java6 / 7问题的更多详细信息阅读 TJ的回答的讨论。

For more details on the Java6/7 issue also read discussion of TJ's answer.

编辑: 我做了一些快速测试。两种方法(显式/魔术)都具有相同的性能。

I did some quick tests. Both ways of casting (explicit/magic) have the same performance.

推荐答案

由于Java中的每个原始数字都被转换为拳击当需要一个对象时(在我们的例子中为 Long ),并且每个盒装数字是 Number 的最实例这样做是:

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();

这里的危险与往常一样, Object 我们要转换不是类型 Number ,在这种情况下,您将获得一个 ClassCastException 。您可以检查对象的类型,如

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) ...

如果您希望防止类转换异常,而是提供默认值,如 0.0 。同样默默无闻的方法并不总是一个好主意。

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.

这篇关于Java:许多方法将一个(长)对象转换为双重的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆