相信很多小伙伴们都有个印象,就是在Integer的实现中,如果value的值在-128到127之间,是有一个缓存的概念的,也就是说:如果值在-128到127之间,这两个对象应该是相等的,对吧?缓存嘛!
事实是这样的么?
我们看看下面的代码会输出什么
public static void main(String[] args) {
Integer i1 = new Integer(1);
Integer i2 = new Integer(1);
System.out.println(i1 == i2);
}
i1和i2都是1,Integer又会用到缓存,所以应该输出true,实际输出:false
这。又是因为什么呢?不是会用到缓存么?未必!
我们进入Integer看看
没错,new Integer(int value),没有用到缓存!
那什么情况下会用呢?继续在Integer源码中排查发现:
缓存IntegerCache定义:
/**
* Cache to support the object identity semantics of autoboxing for values between
* -128 and 127 (inclusive) as required by JLS.
*
* The cache is initialized on first usage. The size of the cache
* may be controlled by the {@code -XX:AutoBoxCacheMax=<size>} option.
* During VM initialization, java.lang.Integer.IntegerCache.high property
* may be set and saved in the private system properties in the
* sun.misc.VM class.
*/
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;
...
缓存的使用:
/**
* Returns an {@code Integer} instance representing the specified
* {@code int} value. If a new {@code Integer} instance is not
* required, this method should generally be used in preference to
* the constructor {@link #Integer(int)}, as this method is likely
* to yield significantly better space and time performance by
* caching frequently requested values.
*
* This method will always cache values in the range -128 to 127,
* inclusive, and may cache other values outside of this range.
*
* @param i an {@code int} value.
* @return an {@code Integer} instance representing {@code i}.
* @since 1.5
*/
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
原来,在静态方法valueOf中才用到了这个缓存。
Integer i = 1; //等价于:Integer i = Integer.valueOf(1)
public static void main(String[] args) {
Integer i1 = 1;
Integer i2 = 1;
System.out.println(i1 == i2);
}
输出:
这里,输出了true,验证了确实用到了缓存。
但是,用==号去判断两个Integer是否相等?这个也有不妥,是个容易忽略掉的坑,如果这里不是用到缓存,那大概率业务上是要出错的!
两个Integer如果==去比较那比较的是两个引用而非值,对象之间的比较还是应该用equals而不是==,这个习惯应该注意保持,不能因为它是Integer就自然而然的当成int去用==去比较值了,这种想法是不对的~