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);
相关文章
相关标签/搜索