日常编码bug汇总
持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第14天,点击查看活动详情
1. Integer 的比较大小缓存
Integer.valueOf()后用==比较,导致的生产bug;
Integer.valueOf()会直接缓存-127到128的Integer对象,因此,在valueOf()方法中,如果值在-127-128之间,都会直接返回缓存中的该对象而不会重新生成对象,引用地址当然相同了
Integer a = Integer.valueOf(3);
Integer b = 3;
a == b // true
Integer a = Integer.valueOf(200);
Integer b = 200;
a == b // false
valueof()缓存
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
IntegerCache 类
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() {}
}
在java6之后,Integer的缓存中还可以通过Integer.IntegerCache.high来设置最大值

**为什么会有缓存**
```txt
因为基本数据类型中,使用包装类包装数值时会创建大量对象,如果没有缓存的话,会有大量的包装类被创建,占用内存,降低效率。选择最常用的数值范围设置缓存机制,就可以优化这一现象.这样就避免了创建大量的对象.
以下几个缓存类都是包装类型的内部类
ByteCache:缓存Byte对象
ShortChche:缓存Short对象
LongChche:缓存Long对象
CharacterChche:缓存Character对象
Byte,Short,Long的缓存范围都是-128-127,Character的缓存范围是0-127,除了Integer,其他的缓存范围都是固定的
所以Integer的比较大小还是要用equals()方法.而且在比较两个Integer对象时可以用Objects.equals(a,b),来避免a.equals(b);时a是null的情况导致出现的NPE异常.