这两种方法有什么区别? 它们彷佛对我作彻底同样的事情(也适用于parseFloat()
, parseDouble()
, parseLong()
等,它们与Long.valueOf(string)
有何不一样? html
编辑:此外,哪一个更可取,而且习惯上使用得更多? java
咱们应根据须要使用任何一种。 在ValueOf实例化对象的状况下。 若是咱们只须要一些文本的值,它将消耗更多的资源,那么咱们应该使用parseInt,parseFloat等。 api
若是检查Integer类,则将找到调用parseInt方法的valueof。 调用API的值时,最大的区别是缓存。 若是值介于-128到127之间,则会缓存它。有关更多信息,请在下面的连接中找到 缓存
http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html oracle
看一下Java源码: valueOf
使用parseInt
: spa
/** * Parses the specified string as a signed decimal integer value. * * @param string * the string representation of an integer value. * @return an {@code Integer} instance containing the integer value * represented by {@code string}. * @throws NumberFormatException * if {@code string} cannot be parsed as an integer value. * @see #parseInt(String) */ public static Integer valueOf(String string) throws NumberFormatException { return valueOf(parseInt(string)); }
parseInt
返回int
code
/** * Parses the specified string as a signed decimal integer value. The ASCII * character \u002d ('-') is recognized as the minus sign. * * @param string * the string representation of an integer value. * @return the primitive integer value represented by {@code string}. * @throws NumberFormatException * if {@code string} cannot be parsed as an integer value. */ public static int parseInt(String string) throws NumberFormatException { return parseInt(string, 10); }
公共静态整数valueOf(String s) orm
结果是一个Integer对象,它表示字符串指定的整数值。 htm
换句话说,此方法返回一个等于如下值的Integer对象:new Integer(Integer.parseInt(s)) 对象
因为valueOf返回一个新的Integer对象,为何下面的代码正确?
String base5String = "230"; int result = Integer.valueOf(base5String);