java中parseInt()和valueOf()之间的区别? [英] Different between parseInt() and valueOf() in java?
问题描述
parseInt()
与valueOf()
有何不同?
它们似乎对我做着完全相同的事情(parseFloat()
,parseDouble()
,parseLong()
等也是如此,它们与Long.valueOf(string)
有何不同?
They appear to do exactly the same thing to me (also goes for parseFloat()
, parseDouble()
, parseLong()
etc, how are they different from Long.valueOf(string)
?
还有,其中哪一种是更可取的,并且习惯上使用得更多?
Also, which one of these is preferable and used more often by convention?
推荐答案
Integer.parseInt(String)
.但是,valueOf(String)
返回一个 new
Integer()
对象,而parseInt(String)
返回一个原语int
.
Well, the API for Integer.valueOf(String)
does indeed say that the String
is interpreted exactly as if it were given to Integer.parseInt(String)
. However, valueOf(String)
returns a new
Integer()
object whereas parseInt(String)
returns a primitive int
.
如果您想享受 Integer.valueOf(int)
,您也可以使用这种令人讨厌的方法:
If you want to enjoy the potential caching benefits of Integer.valueOf(int)
, you could also use this eyesore:
Integer k = Integer.valueOf(Integer.parseInt("123"))
现在,如果想要的是对象而不是原始对象,则使用valueOf(String)
可能比用parseInt(String)
制作新对象更具吸引力,因为前者在Integer
,Long
中始终存在,Double
等
Now, if what you want is the object and not the primitive, then using valueOf(String)
may be more attractive than making a new object out of parseInt(String)
because the former is consistently present across Integer
, Long
, Double
, etc.
这篇关于java中parseInt()和valueOf()之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!