128陷阱指的是,两个Integer数据类型在一定范围内用==判断,会返回true。这个默默人范围是(-128~127)
默认范围是(-128~127)的结果,原因是:Integer在初始化的时候有一个cache数组,这个数组默认范围是-128~127之间。在这个范围内,Integer变量指向的是这个数组里面的一个元素。所以用==判断时,返回的结果为true(判断的是同一个对象的地址)。
public static void main(String[] args) {
Integer a1=-128;
Integer a2=-128;
Integer a3=127;
Integer a4=127;
Integer a5=128;
Integer a6=128;
System.out.println(a1==a2);//true
System.out.println(a3==a4);//true
System.out.println(a5==a6);//false
Integer a7=new Integer(127);
Integer a8=new Integer(127);
System.out.println(a7==a8);//false
}
如上图所示,Integer数据类型的值在(-128~127)之间,用==比较返回true;超出这个范围返回false。如果new一个Integer对象的话,那么比较的是两个不同的对象,返回false(new出来的对象,不存在“128陷阱”)
源码:
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
初始化cache数组的源码:
private static class IntegerCache {
static final int low = -128;
static final int high;
static final Integer[] cache;
static Integer[] archivedCache;
static {
// high value may be configured by property
int h = 127;
String integerCacheHighPropValue =
VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
if (integerCacheHighPropValue != null) {
try {
h = Math.max(parseInt(integerCacheHighPropValue), 127);
// Maximum array size is Integer.MAX_VALUE
h = Math.min(h, Integer.MAX_VALUE - (-low) -1);
} catch( NumberFormatException nfe) {
// If the property cannot be parsed into an int, ignore it.
}
}
high = h;
// Load IntegerCache.archivedCache from archive, if possible
CDS.initializeFromArchive(IntegerCache.class);
int size = (high - low) + 1;
// Use the archived cache if it exists and is large enough
if (archivedCache == null || size > archivedCache.length) {
Integer[] c = new Integer[size];
int j = low;
for(int i = 0; i < c.length; i++) {
c[i] = new Integer(j++);
}
archivedCache = c;
}
cache = archivedCache;
// range [-128, 127] must be interned (JLS7 5.1.7)
assert IntegerCache.high >= 127;
}
private IntegerCache() {}
}
除了Integer外,其他包装类也有缓存技术
基本类型 | 装箱类型 | 是否缓存 | 缓存范围 | 取值范围 |
---|---|---|---|---|
byte | Byte | 是 | -128~127 | -128~127 |
short | Short | 是 | -128~127 | -2^15~(2^15-1) |
int | Integer | 是 | -128~127 | -2^31~(2^31-1) |
long | Long | 是 | -128~127 | -2^63~(2^63-1) |
float | Float | 否 | ||
double | Double | 否 | ||
char | Boolean | 是 | \u0000~\u0071 | \u0000~\uffff |
boolean | Character | 是 | true,false | true,false |