Java中valueOf与parseInt方法比较

文章转载:Java中valueOf与parseInt方法比较

描述

来自JDK8官方文档,这里只比较参数为String的两个方法
1.public static int parseInt(String s)

Parses the string argument as a signed decimal integer. The characters in the string must all be decimal digits, except that the first character may be an ASCII minus sign ‘-’ (‘\u002D’) to indicate a negative value or an ASCII plus sign ‘+’ (‘\u002B’) to indicate a positive value. The resulting integer value is returned, exactly as if the argument and the radix 10 were given as arguments to the parseInt(java.lang.String, int) method.
Parameters:
s - a String containing the int representation to be parsed
Returns:
the integer value represented by the argument in decimal.
Throws:
NumberFormatException - if the string does not contain a parsable integer.

2.public static Integer valueOf(String s)

Returns an Integer object holding the value of the specified String. The argument is interpreted as representing a signed decimal integer, exactly as if the argument were given to the parseInt(java.lang.String) method. The result is an Integer object that represents the integer value specified by the string.
In other words, this method returns an Integer object equal to the value of:
new Integer(Integer.parseInt(s))
Parameters:
s - the string to be parsed.
Returns:
an Integer object holding the value represented by the string argument.
Throws:
NumberFormatException - if the string cannot be parsed as an integer.

比较

首先从返回类型可以看出parseInt返回的是基本类型int,而valueOf返回的是对象。再看valueOf的描述有

new Integer(Integer.parseInt(s))

可以大胆猜测valueOf的内部其实就是调用了parseInt方法。
所以直接去找源码。

 public static Integer valueOf(String s) throws NumberFormatException {
        return Integer.valueOf(parseInt(s, 10));
 }
 public static Integer valueOf(int i) {
    assert IntegerCache.high >= 127;
 if (i >= IntegerCache.low && i <= IntegerCache.high)
        return IntegerCache.cache[i + (-IntegerCache.low)];
    return new Integer(i);
 }
 public static int parseInt(String s) throws NumberFormatException {
    return parseInt(s,10);
 }

结语

因为JDK5以后实现了自动拆装箱,因而两者的差别也不是特别大了,但是从效率上考虑,建议首先考虑parseInt方法。

猜你喜欢

转载自blog.csdn.net/cherry_xiu/article/details/81085228
今日推荐