這兩種方法有什麼區別? 它們彷佛對我作徹底同樣的事情(也適用於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);