先来说结论:对于new生成的两个对象,即使是内容相同结果始终是false;对于两个非new生成的Integer对象,进行比较的时候,如果变量的值在-128~127之间,则返回true,否则返回false。
public static void main(String[] args) {
Integer i1=11;
Integer i2=11;
System.out.println(i1==i2);//true
Integer i3=127;
Integer i4=127;
System.out.println(i3==i4);//true
Integer i5=128;
Integer i6=128;
System.out.println(i5==i6);//false
}
原理(自动装箱)
JAVA在编译Integer i1=11;
时会自动调用ValueOf方法,查看源码知ValueOf方法的定义如下:
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
上面的Low=-128,high=127,在这个范围中会直接从缓存池中引用,不在这个范围就new一个,那么一定返回false啦