您的位置:首页 > 其它

Integer 中的缓存类IntegerCache

2016-12-19 10:07 288 查看
Cache为[-128,127],IntegerCache有一个静态的Integer数组,在类加载时就将-128 到 127 的Integer对象创建了,并保存在cache数组中,一旦程序调用valueOf 方法,如果取的值是在-128 到 127 之间就直接在cache缓存数组中去取Integer对象,超出范围就new一个对象。

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) {
int i = parseInt(integerCacheHighPropValue);
i = Math.max(i, 127);
// Maximum array size is Integer.MAX_VALUE
h = Math.min(i, Integer.MAX_VALUE - (-low));
}
high = h;

cache = new Integer[(high - low) + 1];
int j = low;
for(int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++);
}

private IntegerCache() {}
}


Integer i = 127;
Integer j = 127;
System.out.println(i==j);//true
Integer i1 = 128;
Integer j1 = 128;
System.out.println(i1==j1);//false
Integer i2 = new Integer(127);
Integer j2= new Integer(127);
System.out.println(i2==j2);//false
System.out.println(200 == i); //false
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: