public static void main(String[] args) {
Integer a = 127;
Integer b = 127;
int c = 127;
b.intValue();
System.out.println((a == b) + " " + (a == c));
a = 128;
b = 128;
c = 128;
System.out.println((a == b) + " " + (a == c));
}
利用javap命令对类进行反编译,从而分析其底层原理。
以上是第一次println前的反编译结果,可以看到,执行了两次valueOf,也就是,
Integer a = 127;
Integer b = 127;
这两步,执行了Integer类的valueOf方法,其部分源码如下:
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 final Integer cache[];
...
}
可以看到,如果 i >= IntegerCache.low && i <= IntegerCache.high,valueOf会返回IntegerCache.cache数组中的数,否则new一个新的对象。
而根据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.
*/
可以看到,low和high的默认值是-128和127,而high的值可以通过-XX:AutoBoxCacheMax=<size>命令设置。
回到最初的程序,a与b的两次比较,
第一次的值是127,在区间[-128, 127]内,因此a==b的结果是true,
而第二次的值是128,在区间外,因此a==b的结果为false。
继续看反汇编的结果
可以看到,a与c比较时,调用了intValue方法,也就是将Integer类转化为int值,再进行比较,因此a与c的两次比较,结果都为true。