浅谈Java“128陷阱”
这是我在学习java的自动装箱、自动拆箱时遇到的一个有意思的问题,经过查看源码后了解原理,特此记录
- 测试程序
public static void main(String[] args) {
Integer a =101;
Integer b =101;
System.out.println(a==b);
Integer c =1001;
Integer d =1001;
System.out.println(c==d);
int e =101;
int f =1001;
System.out.println(a==e);
System.out.println(c==f);
}
- 测试结果
true
false
true
true
Java 基本类型的包装类的大部分都实现了常量池技术,即Byte,Short,Integer,Long,Character,Boolean;前面 4 种包装类默认创建了数值[-128,127] 的相应类型的缓存数据,因此如果超出了这个范围就会new一个新的Integer类,所以当我们用“==”比较两个超出范围的值时就会因为是两个不一样的Integer对象,所以返回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() {}
}
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}

被折叠的 条评论
为什么被折叠?



