简体   繁体   English

什么是Double.valueOf(String s)和Double.ParseDouble(String s)之间的区别?

[英]Whats the difference between Double.valueOf(String s) and Double.ParseDouble(String s)?

As I understand the doc, ParseDouble function made something like : 据我所知,ParseDouble函数就像这样:

 Double parseDouble(String s) throws ... {       
      return new Double(Double.valueOf(s));
 }

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. 逻辑是相同的,但Double.valueOf()的返回值返回一个堆分配的Double对象,其中parseDouble返回一个原始double。 Your code example is not quite correct. 您的代码示例不太正确。 The java source reads: 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());
}

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. 但是,我仍然主张根据所需的结果使用合适的一个。

parseDouble返回一个double value ,valueOf返回一个Double类型的新object

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 wrapped double value in a Double . 返回Double包装 double值。

valueOf returns a double, parseDouble returns a Double. valueOf返回一个double,parseDouble返回一个Double。 Use whichever suits your needs. 使用适合您需求的任何一种。

In Java 6 the reverse is true: 在Java 6中,情况恰恰相反:

Double valueOf(String s) throws ... {       
      return new Double(Double.parseDouble(s));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM