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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 20:42:34  来源:igfitidea点击:

Casting an instance of Object to primitive type or Object Type

javacastingprimitive-typesobject-type

提问by Gautam

when I need to cast an instance of type Objectto 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 objectis null - the second will throw a NullPointerException. So if it's valid for objectto 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 doubleis 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 语言增强页面中不清楚为什么这是真的。