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.valueOf(String)
确实说 String
被解释就像它被赋予 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)
创建一个新对象更有吸引力code> 因为前者始终存在于 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屋!