关于Integer和int的==比较:
对于int基本类型,==比较的是值
对于Integer类型比较的是内存地址,相同的引用:
- new一个包装类,地址改变,一定不会相等;
注意看注释
public static void main(String[] args) {
Integer a=100;
int a1=100;
System.out.println("a==a1 "+ (a==a1));
Integer b= Integer.valueOf(200);
Integer bb=200;
System.out.println("b==bb "+ (b==bb));//非new出来的Integer,如果数在-128到127之间,则是true
int b2=200;
System.out.println("b==b2 "+ (b==b2));//Integer与int进行==比较时,不管是直接赋值,还是new创建的对象,只要跟int比较就会拆箱为int类型,所以就是相等的。
Integer c=new Integer(100);
System.out.println("a==c "+ (a==c));//Integer与new Integer不会相等。不会经历拆箱过程,因为它们存放内存的位置不一样。
System.out.println("a1==c "+ (a1==c));
}
- 128陷阱:
在小于127大于-128的时候,自动装箱的是同一个地址存在的数值.大于127时,自动装箱的不在同一个地址,故==比较结果为false
查看valueOf()源码:从源码中可以发现,在 -128—127 之间的数值都存储在有一个catch数组中, 当在-128-127之间进行自动装箱的时候,就直接返回该值在内存当中的相同地址 ,是相同的引用,则用==判断返回true。
public static Integer valueOf(int i) {
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);
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() {}
}