java Double.valueOf(String s) 和 Double.ParseDouble(String s) 有什么区别?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3708931/
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
Whats the difference between Double.valueOf(String s) and Double.ParseDouble(String s)?
提问by oyo
As I understand the doc, ParseDouble function made something like :
据我了解文档,ParseDouble 函数做了类似的事情:
Double parseDouble(String s) throws ... {
return new Double(Double.valueOf(s));
}
回答by Michael Barker
The logic is the same, but the return value of Double.valueOf() return a heap allocated Double object, where as parseDouble returns a primitive double. Your code example is not quite correct. The java source reads:
逻辑相同,但 Double.valueOf() 的返回值返回堆分配的 Double 对象,而 parseDouble 返回原始双精度值。您的代码示例不太正确。java源码如下:
public static double parseDouble(String s) throws NumberFormatException {
return FloatingDecimal.readJavaFormatString(s).doubleValue();
}
public static Double valueOf(String s) throws NumberFormatException {
return new Double(FloatingDecimal.readJavaFormatString(s).doubleValue());
}
回答by dogbane
Depends on whether you want a double or a Double. Although with autoboxing, it doesn't really matter. If you are doing something very intensive then you want to avoid using doubles in places where Doubles are needed in order to avoid the autoboxing overhead. But, it would need to be very, very, very, intensive before it actually makes any difference.
取决于你想要双人还是双人。虽然使用自动装箱,但这并不重要。如果您正在做一些非常密集的事情,那么您希望避免在需要双精度的地方使用双精度,以避免自动装箱开销。但是,它需要非常、非常、非常、密集,才能真正发挥作用。
I would still, however, advocate using the proper one according to the desired result.
但是,我仍然主张根据所需的结果使用适当的方法。
回答by Buhake Sindi
Simple,
简单的,
public static double parseDouble(String s) throws NumberFormatException
returns a java primitive double, while
返回一个 java 原语double,而
public static Double valueOf(String s) throws NumberFormatException
returns a wrappeddouble value in a Double.
在 a 中返回一个包装的双精度值Double。
回答by stacker
parseDoublereturns a double value, valueOf returns a new objectof type Double.
parseDouble返回 a double value, valueOf 返回一个 newobject类型Double。
回答by PaulJWilliams
valueOf returns a double, parseDouble returns a Double. Use whichever suits your needs.
valueOf 返回一个双精度值,parseDouble 返回一个双精度值。使用适合您需求的任何一种。
回答by gpeche
In Java 6 the reverse is true:
在 Java 6 中,情况正好相反:
Double valueOf(String s) throws ... {
return new Double(Double.parseDouble(s));
}

