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方法。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值