看看这个valueOf(int)的源代码吧
public static Integer valueOf(int i) {
final int offset = 128;
if (i >= -128 && i <= 127) { // must cache
return IntegerCache.cache[i + offset];
}
return new Integer(i);
}
里面有一段判断数字是否在-128和127之间的代码,如果是的话,则使用了一个缓冲。
我们看看缓冲的部分
private static class IntegerCache {
private IntegerCache(){}
static final Integer cache[] = new Integer[-(-128) + 127 + 1];
static {
for(int i = 0; i < cache.length; i++)
cache[i] = new Integer(i - 128);
}
}
这个内置的类,就是给这256个Integer进行缓冲,可以减少大量的内存占用和垃圾回收消耗。
最后看看new Integer(int)吧
private final int value;
public Integer(int value) {
this.value = value;
}
没啥说的,new肯定是要占用新的内存的,当然以后的费用还会增加。
所以,使用valueOf来代替new 是绝对可以增加系统的健壮性的。