在整数包装类型之间值的比较,推荐使用equals;
在Java基本数据类型的包装类型中,大部分都用到了缓存机制来提升性能
Byte、Short、Integer、Long默认创建了数值【-128,127】的相应类型的缓存数据,
character创建了【0,127】范围的缓存数据,Boolean直接返回true或false
Integer缓存源码:
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 {
// high value may be configured by property
int h = 127;
}
}
对于Integer var=?在-128和127之间,就会使用的缓存中的对象,这个区间类的值可以使用==来进行判断,但是这个区间外的值就会创建一个新的对象,此时就推荐使用equals来进行比较;
Integer a = 30;
Integer b = new Integer(30);
System.out.println(a == b);
上面输出的结果为false
a在Integer的缓存机制内,会使用缓存中对象,b是新建的一个对象,所以它们比较的结果就为false