看出对于范围 [-128,127] 的整数,valueOf 方法做了特殊处理。采用
IntegerCache.cache[i + (-IntegerCache.low)]; 这个方法。
查看 IntegerCache 类的实现为:
private static class IntegerCache {
static final int low = -128; //最小值是固定的
static final int high;
static final Integer cache[];//cache 缓存是一个存放 Integer
类型的数组
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) {
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);
}
high = h;
cache = new Integer[(high - low) + 1]; //初始化数组
int j = low;
//缓存区间数据
for(int k = 0; k < cache.length; k++)
//将-128~127 包装成 256 个对象存入缓存
cache[k] = new Integer(j++);
}
private IntegerCache() {}
}
IntegerCache 初始化后内存中就有 Integer 缓冲区 cache[]了,-128~127 区间的 int
值有其对应的的包装对象。这就是 valueOf 方法真正的优化方法,当-128=
public class ZhuangXaing {
public static void main(String[] args) {
Integer i= new Integer(12);
Integer j=12;