parseInt和valueOf在Java中的區別?

這兩種方法有什麼區別? 它們彷佛對我作徹底同樣的事情(也適用於parseFloat()parseDouble()parseLong()等,它們與Long.valueOf(string)有何不一樣? html

編輯:此外,哪一個更可取,而且習慣上使用得更多? java


#1樓

  1. 對於ValueOf->,它將建立一個Integer對象。 不是原始類型,也不是靜態方法。
  2. 若是是ParseInt.ParseFloat->,則返回各自的原始類型。 而且是靜態方法。

咱們應根據須要使用任何一種。 在ValueOf實例化對象的狀況下。 若是咱們只須要一些文本的值,它將消耗更多的資源,那麼咱們應該使用parseInt,parseFloat等。 api


#2樓

若是檢查Integer類,則將找到調用parseInt方法的valueof。 調用API的值時,最大的區別是緩存。 若是值介於-128到127之間,則會緩存它。有關更多信息,請在下面的連接中找到 緩存

http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html oracle


#3樓

看一下Java源碼: valueOf使用parseIntspa

/**
 * 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);
}

#4樓

公共靜態整數valueOf(String s) orm

  1. 該參數被解釋爲表示一個帶符號的十進制整數,就像將參數提供給parseInt(java.lang.String)方法同樣。
  2. 結果是一個Integer對象,它表示字符串指定的整數值。 htm

  3. 換句話說,此方法返回一個等於如下值的Integer對象:new Integer(Integer.parseInt(s)) 對象


#5樓

因爲valueOf返回一個新的Integer對象,爲何下面的代碼正確?

String base5String = "230";
int result = Integer.valueOf(base5String);
相關文章
相關標籤/搜索