Differences among parseInt(), intValue(), valueOf()

471 查看

Differences among parseInt(), intValue(), valueOf()

From StackOverFlow:

parseInt returns primitive integer type (int), whereby valueOf returns java.lang.Integer, which is the object representative of the integer. There are circumstances where you might want an Integer object, instead of primitive type.

Of course, another obvious difference is that intValue is an instance method whereby parseInt is a static method.

总的来说:

parseIntvalueOf都可以返回String的数值,intValue是将Integer转换成int返回。
parseIntvalueOf返回值的类型不同:parseInt返回的是primitive type: int,而valueOf返回的是object: Integer.
那么,哪一个更快呢?其实,返回值类型不同,这样的比较是没有意义的。但是看到这样一个问题,不妨歪解一下,看java doc中是怎么实现valueOf吧:

public static Integer valueOf(String string) throws NumberFormatException {
    return valueOf(parseInt(string));
}

可见valueOf调用了parseInt,因此parseInt更快。

看到另一个例子,

int size = Integer.valueOf("abc").intValue();

这样冗赘的语句是不是可以修改一下呢?

科科。