java中的parseInt和valueOf之间的区别? [英] Difference between parseInt and valueOf in java?
问题描述
这两种方法有什么区别?他们似乎对我做了完全相同的事情(也适用于 parseFloat()
, parseDouble()
, parseLong()
等,它们与 Long.valueOf(字符串)
的区别?
What's the difference between these two methods? 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 of these is preferable and used more often by convention?
推荐答案
嗯,适用于 <$的API c $ c> Integer.valueOf(String) 确实说 String
的解释方式与< a href =http://java.sun.com/javase/6/docs/api/java/lang/Integer.html#parseInt(java.lang.String) =noreferrer> Integer.parseInt(String)
。然而, valueOf(String)
返回 new
Integer()
object而 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
.
如果你想享受 <$的潜在缓存优势c $ c> 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创建一个新对象更有吸引力(字符串)
因为前者始终存在于整数
,长
, 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屋!