128陷阱
基本介绍
首先我们从一个例子来看一下什么是128陷阱
来看一下下面代码的输出是什么?
Integer a = 127;
Integer b = 128;
Integer a1 = 127;
Integer b1 = 128;
System.out.println(a == a1);
System.out.println(b == b1);
揭晓答案
这是为什么呢?
首先我们需要了解自动装箱机制
我们知道在为自动装箱的过程是Integer.valueOf()
来进行初始化,我们来看一下源码
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;
}
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
通过源码我们可以发现,IntegerCache类中存在有一个缓存数组,大小是 -128 ~ 127时,是直接从缓存数组中取值,而超出这个范围时new新的对象,所以在 -128 ~ 127范围中进行比较,比较的是值,而超出这个范围比较的是地址,这就是我们常说的128陷阱。
自动装箱规范要求 boolean、byte、char 127, 介于 -128 ~ 127 之间的 short 和 int 被包装到固定的对象中。例如,如果在前面的例子中将 a 和 b 初始化为 100,对它们进行比较的结果一定成立。
------- java核心技术卷(第十版) 1
这也是我们比较包装类时为什么推荐使用equals方法的原因之一
拓展
Long类型也是存在128陷阱的,他源码中也维护了一个-128~127的缓存数组
Long c = 128L;
Long c1 = 128L;
System.out.println(c == c1);
输出为flase