java 将 Object 的实例转换为原始类型或对象类型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15742560/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Casting an instance of Object to primitive type or Object Type
提问by Gautam
when I need to cast an instance of type Object
to a double , which of the following is better and why ?
当我需要将 type 的实例Object
转换为 double 时,以下哪个更好,为什么?
Double d = (Double) object;
Double d = (Double) object;
Or
或者
double d = (double) object;
double d = (double) object;
回答by Jon Skeet
The difference is that the first form will succeed if object
is null - the second will throw a NullPointerException
. So if it's valid for object
to be null, use the first - if that indicates an error condition, use the second.
不同之处在于第一种形式在object
为 null 时会成功——第二种形式将抛出一个NullPointerException
. 因此,如果它为object
空有效,请使用第一个 - 如果这表示错误情况,请使用第二个。
This:
这:
double d = (double) object;
is equivalent to:
相当于:
Double tmp = (Double) object;
double t = tmp.doubleValue();
(Or just ((Double)object).doubleValue()
but I like separating the two operations for clarity.)
(或者只是((Double)object).doubleValue()
为了清楚起见,我喜欢将这两个操作分开。)
Note that the cast to double
is only valid under Java 7 - although it's not clear from the Java 7 language enhancements pagewhy that's true.
请注意,强制转换double
仅在 Java 7 下有效 - 尽管从Java 7 语言增强页面中不清楚为什么这是真的。