简体   繁体   中英

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

As I understand the doc, ParseDouble function made something like :

 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. Your code example is not quite correct. The java source reads:

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

public static Double valueOf(String s) throws NumberFormatException

returns a wrapped double value in a Double .

valueOf returns a double, parseDouble returns a Double. Use whichever suits your needs.

In Java 6 the reverse is true:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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