[英]What's the difference between calling Double.valueOf(String s) and new Double(String s)?
So I've got a String and I want to create a Double object with the String as a value. 所以我有一个String,我想创建一个Double对象,并将String作为值。
I can call 我可以打电话
Double myDouble = new Double (myString);
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. 额外的功劳 :字符串可能为null ,在这种情况下我希望Double为null ,但上述两者都抛出NullPointerException。 Is there a way of writing 有没有写作方式
Double myDouble = myString == null ? null : Double.valueOf(myString);
in less code? 用更少的代码?
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. 从字符串中获取Double的第二种方法可以更快,因为可以从缓存返回值。
Regarding the second question, you may create a helper null safe method which would return a null instead of throwing NullPointerException. 关于第二个问题,您可以创建一个helper null safe方法,该方法将返回null而不是抛出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 来自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);
}
Depends on the implementation. 取决于实施。 openJDK 6 b14 uses this implementation of Double(String s)
: openJDK 6 b14使用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. 所以它调用valueOf(String s)
在内部,并且与直接调用该方法必须是低效率的。
No difference whatsoever, at least in Oracle JDK 1.6: 没有任何区别,至少在Oracle JDK 1.6中是这样:
public Double(String s) throws NumberFormatException {
// REMIND: this is inefficient
this(valueOf(s).doubleValue());
}
如果您担心性能,则应考虑使用原语。
double myDouble = Double.parseDouble(myString);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.