包装器类 Integer 的128陷阱
描述:是指两个Integer类型变量,通过==进行地址比较时,值为-128到127输出为true,而其他的值比较会输出false
原因
Integer的源码中,由于Integer的自动装箱方法valueOf的关系
//源码
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
由源码可以看到,在i >= IntegerCache.low && i <= IntegerCache.high时,是从cache数组中获取值,而其他范围则新实例化一个对象,这样==判断时,返回false
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() {}
}
从内部类IntegerCache可以看到,只要Integer第一次被使用都,静态内部类就被加载,加载的时候会创建-128到127的Integer对象,同时创建一个数组cache来缓存这些对象
for(int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++);
所以当使用valueOf方法创建对象时,就直接返回已经缓存的对象,不会创建新对象,当使用new关键字or使用valueOf()方法创建小于-128大于127的值对象时,就会创建新对象。
而Integer i = 127 自动装箱及调用valueOf方法,所以存在128陷阱问题