摘要:Integer等包装类判断相等时,最好使用equals方法(原因:因为包装类源码中隐藏一个一个关于缓存的大坑)。
代码示例:
public static void main(String[] args) {
int a = 150;
int b = 150;
Integer c = 150;
Integer d = 150;
Integer e = 10;
Integer f = 10;
System.out.println(a == b);//true
System.out.println(c == d);//false
System.out.println(e == f);//true
System.out.println(c.equals(d));//true
}
以上结果只有“c==d”返回的是false,原因在jdk的源码中,一下是Integer的部分源码:
static final int low = -128;
static final int high;
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);
}
可以很明显的看出当传入的数值在-128到127之间的时候,Integer并没有使用new来创建,而是采用IntegerCache的缓存类中直接获取。“==”判断的是堆内存的存放位置,当值为150的时候,c、d两个数是通过new 关键字分别new出来的对象,所以用“==”判断返回false。