parseInt()如何不同于valueOf() ?

它们似乎对我做了完全相同的事情(也适用于parseFloat(), parseDouble(), parseLong()等,它们与Long.valueOf(字符串)有什么不同?

另外,按照惯例,哪一个更可取,更常用呢?


当前回答

查看Java源代码:valueOf使用parseInt:

/**
 * 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(不是整数)

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

其他回答

查看Java源代码:valueOf使用parseInt:

/**
 * 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(不是整数)

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

如果你检查Integer类,你会发现valueof调用parseInt方法。最大的区别是当你调用valueof API时缓存。如果值在-128到127之间,它会缓存。更多信息请参见下面的链接

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

parse*变体返回基本类型,valueOf版本返回对象。我相信valueOf版本还将使用内部引用池为给定值返回SAME对象,而不仅仅是具有相同内部值的另一个实例。

Integer.valueOf(s)

类似于

new Integer(Integer.parseInt(s))

区别在于valueOf()返回一个Integer,而parseInt()返回一个int(基本类型)。还要注意,valueOf()可以返回一个缓存的Integer实例,这可能会导致令人困惑的结果,其中==测试的结果似乎间歇性地正确。在自动装箱之前,便利性可能会有所不同,在java 1.5之后,这就不重要了。

此外,Integer.parseInt(s)也可以接受基本数据类型。

对于ValueOf ->,它正在创建一个Integer对象。不是基元类型,也不是静态方法。 在ParseInt的情况下。ParseFloat ->返回各自的基本类型。And是一个静态方法。

我们可以根据需要使用任何一种。对于ValueOf,因为它正在实例化一个对象。如果我们只需要一些文本的值,它会消耗更多的资源,那么我们应该使用parseInt,parseFloat等。