128陷阱举例
public static void main(String[] args) {
Integer a = 100;
Integer b = 100;
Integer a1 = 200;
Integer b1 = 200;
System.out.println(a==b);
System.out.println(a1==b1);
}
结果:
输出结果表明a和b指向的是同一个对象,而a1和b1指向的是不同的对象。通过看源码可知原因,下面这段代码是Integer的valueOf方法的具体实现:
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() {}
}
从这2段代码可以看出,在通过valueOf方法创建Integer对象的时候,如果数值在[-128,127]之间,便返回指向IntegerCache.cache中已经存在的对象的引用;否则创建一个新的Integer对象。
上面的代码中a和b的数值为100,因此会直接从cache中取已经存在的对象,所以a和b指向的是同一个对象,而a1和b1则是分别指向不同的对象。
这就是128陷阱,所有包装器类型都有128陷阱,当数不在-128到127这个范围时,指向的就是两个不同的地方了,这时候比较就需要手动拆箱。
==和equals()与128陷阱
public static void main(String[] args) {
int a = 10;
int b = 300;
Integer a1 = 10;
Integer b1 = 300;
Integer a2=new Integer(a1);
Integer b2=new Integer(b1);
System.out.println(a==a1);
System.out.println(a==a2);
System.out.println(b==b1);
System.out.println(b==b2);
}
结果:
- a,b是int类型,是基本类型,用==去进行比较的话,比较的是他们的值
- a1,a2是integer类型,会自动拆箱,拆成10这个值来进行比较,所以都是true
只有下面这种是false
因为a2是一个new出来的integer,所以a1、a2指向的地址不同,如果这时候要比较他们的值需要用equals()