Integer 类的 parseInt(String s) 和 valueOf(String s) 的区别
问题
在看代码时,如下代码提出了警告,并建议进行修改
修改前代码如下:
int policyYear = Integer.valueOf(calculateParamMap.get(CommonConstant.POLICY_YEAR_STRING));
警告信息如下:
Redundant boxing inside 'Integer.valueOf(calculateParamMap.get(CommonConstant.POLICY_YEAR_STRING))'
修改后代码如下:
int policyYear = Integer.parseInt(calculateParamMap.get(CommonConstant.POLICY_YEAR_STRING));
警告的意思大致就是重复装箱拆箱了
印象里两个方法并没有什么区别,于是带着好奇点开两个代码的源码,看了下发现这两个方法的用法还是有些区别的
探究
- parseInt(String s) 源码
public static int parseInt(String s) throws NumberFormatException {
return parseInt(s,10);
}
- valueOf(String s) 源码
public static Integer valueOf(String s) throws NumberFormatException {
return Integer.valueOf(parseInt(s, 10));
}
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
结论
通过对比两个方法的源码,其实很容易看出区别
- 两个方法对 String 转 int 的实现都是调用了 parseInt(s,10) 方法
- parseInt(String s) 调用 parseInt(s,10) 方法后直接返回 int 类型值,而 valueOf(String s) 对 parseInt(s,10) 方法的返回值进行了装箱操作,最终返回一个 Integer 类型,这也是为什么上边警告的信息提示我重复装箱拆箱的原因
- 在使用两个方法时,如果仅仅需要一个 int 类型的值还是推荐使用 parseInt(String s) 方法的好,毕竟少了一次拆箱装箱,效率会好很多;如果需要的是 Integer 类型,推荐使用 valueOf(String s) 方法,从其 valueOf(int i) 方法可以看出,其对 -128 到 127 之间的数进行了缓存(缓存最小值 -128,最大值取决于 -XX:AutoBoxCacheMax=xxx 配置,默认是 127 ),如果你需要的 int 在这之内,效率会略有提升
具体缓存代码如下
/**
* Cache to support the object identity semantics of autoboxing for values between
* -128 and 127 (inclusive) as required by JLS.
*
* The cache is initialized on first usage. The size of the cache
* may be controlled by the {@code -XX:AutoBoxCacheMax=<size>} option.
* During VM initialization, java.lang.Integer.IntegerCache.high property
* may be set and saved in the private system properties in the
* sun.misc.VM class.
*/
private static class IntegerCache {
static final int low = -128;
static final int high;
static final Integer cache[];
static {
// high value may be configured by property
int h = 127;
String integerCacheHighPropValue =
sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
if (integerCacheHighPropValue != null) {
try {
int i = parseInt(integerCacheHighPropValue);
i = Math.max(i, 127);
// Maximum array size is Integer.MAX_VALUE
h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
} catch( NumberFormatException nfe) {
// If the property cannot be parsed into an int, ignore it.
}
}
high = h;
cache = new Integer[(high - low) + 1];
int j = low;
for(int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++);
// range [-128, 127] must be interned (JLS7 5.1.7)
assert IntegerCache.high >= 127;
}
private IntegerCache() {}
}