昨天面试的时候被问到
Integer a=128;
Integer b=128;
问 a==b 跟a.equal(b)的结果;
这里就要分Integer值位-128-127的情况
在-128到127的情况下, a==b的值为true; a.equals(b)的值为true;
这里就要分Integer值位小于-128和大于127的情况
在-128到127的情况下, a==b的值为false; a.equals(b)的值为true;
public static Integer valueOf(int i) {
assert IntegerCache.high >= 127;
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
从而导致地址的不同,因此a==b返回值为false;