开发者

What's the difference between calling Double.valueOf(String s) and new Double(String s)?

开发者 https://www.devze.com 2023-02-05 18:09 出处:网络
So I\'ve got a String and I want to create a Double object with the String as a value. I can call Double myDouble = new Double (myString);

So I've got a String and I want to create a Double object with the String as a value.

I can call

Double myDouble = new Double (myString);

开发者_JAVA百科

or I can call

Double myDouble = Double.valueOf(myString);

Is there a difference? I'm guessing the first guarantees a new object is created on the heap and the second might re-use an existing object.

For extra credit: the string might be null, in which case I want the Double to be null, but both the above throw a NullPointerException. Is there a way of writing

Double myDouble = myString == null ? null : Double.valueOf(myString);

in less code?


Depends on the implementation. openJDK 6 b14 uses this implementation of Double(String s):

this(valueOf(s).doubleValue());

So it calls valueOf(String s) internally and must be less efficient compared to calling that method directly.


Your assumption is right. The second way of getting a Double out of String can be faster because the value may be returned from a cache.

Regarding the second question, you may create a helper null safe method which would return a null instead of throwing NullPointerException.


from apache

public static Double valueOf(String string) throws NumberFormatException {
          return new Double(parseDouble(string));
}

&

public Double(String string) throws NumberFormatException {
          this(parseDouble(string));
}

from sun[oracle ] jdk

 public Double(String s) throws NumberFormatException {
    // REMIND: this is inefficient
    this(valueOf(s).doubleValue());
    }

&

public static Double valueOf(double d) {
        return new Double(d);
    }


No difference whatsoever, at least in Oracle JDK 1.6:

public Double(String s) throws NumberFormatException {
// REMIND: this is inefficient
this(valueOf(s).doubleValue());
}


If you are concerned about performance you should consider using a primitive.

double myDouble = Double.parseDouble(myString);


this will either return a valid Double, or null otherwise.

Double myDouble = null;
try {
    myDouble = Double.valueOf(myString);
}
catch (Exception e) { }

it handles even when myString is null

0

精彩评论

暂无评论...
验证码 换一张
取 消