一、什么是128陷阱
首先要了解什么是128陷阱
即:128陷阱指的是2个integer对象直接用==判定,在某个范围内可以判true,而超出这个范围则为false
二、什么时候会产生128陷阱
当2个包装器对象比较大小时
JDK1.5之后,编译器提供了自动拆箱和装箱的功能
创建Integer对象时:
// 自动装箱
Integer b = 128; // 即:Integer b = Integer.valueOf(10);
Integer转换int时
int a = b; // 即:int a = b.intValue();
三、为什么会产生128陷阱
装箱操作的Integer.valueOf
public static Integer valueOf(int i) {
// 如果这个值在low和high之间,则会使用缓存;如果不在则会创建一个Integer对象
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
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);
// 即最大值最小是127
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++);
// 创建一个断言,后面的表达式必须为真,如果为假,则会抛出AssertionError
// range [-128, 127] must be interned (JLS7 5.1.7)
assert IntegerCache.high >= 127;
}
private IntegerCache() {}
}
总结
在创建Integer类型时,如果值在某个特定的范围内,则会使用缓存数组内的值,这个时候两个数字大小的Integer就会相等,即地址相同;如果创建两个超出这个范围的Integer,则会分别创建两个对象,值相同,但是地址不相同,会返回false。