先看代码
public class IntegerTest{
public static void main(String[] args) {
Integer a1 = 12;
Integer a2 = 12;
//#1
System.out.println(a1 == a2 ); //true
Integer b1 = 128;
Integer b2 = 128;
//#2
System.out.println(b1 == b2 ); //false
//#3
Integer c1 = 12 ;
int c2 = 12 ;
System.out.println(c1 == c2 ); //true
//#4
Integer d1 = new Integer(12);
Integer d2 = new Integer(12);
System.out.println(d1 == d2 ); //false
}
}
//#1和#2 的结果不相同的原因是啥了?
a. Integer a =12 ; java 反编译的时候,成为了 Integer a = Integer.valueOf(12);
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
当 i 值为[-128,127]的时候 从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() {}
}
看完IntegerCache类 就知道是啥事了。
//那为啥#4是false了?
因为通过构造函数形成的对象,不会从IntegerCache数组中取实例。
//#3 是从JDSK1.5开始 Integer和int比较的时候 Integer自动拆箱,再进行比较。