看下面这段代码:
public class newTest {
public static void main(String[] args){
Integer t1 = 59;//回去Integer缓存里面取找,找不着会创建一个新的Integer对象
int t2 = 59;//基本类型,与Integer
Integer t3 = Integer.valueOf(59);//取缓存里面寻找
Integer t4 = new Integer(59);//创建新的Integer对象
System.out.println(t1 == t2); // true
System.out.println(t1 == t3); // true
System.out.println(t3 == t4); // false
System.out.println(t1 == t4); // false
System.out.println(t2 == t4); // true
}
}
在上面的代码中,其实t1和t3是等价的,因为t1反编译结果Integer t1 = Integer.valueOf(59);
那么,来看看valueOf这个函数,如下面所示:
public static Integer valueOf(int i) {
assert IntegerCache.high >= 127;
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
从上面可以看出,当数字在-128~127的时候,就会从这个Cache里面找,当数字不在这个区间内,会返回一个新的Integer对象。既然如此,那再看看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) {
int i = parseInt(integerCacheHighPropValue);
i = Math.max(i, 127);
// Maximum array size is Integer.MAX_VALUE
h = Math.min(i, Integer.MAX_VALUE - (-low));
}
high = h;
cache = new Integer[(high - low) + 1];
int j = low;
for(int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++);
}
private IntegerCache() {}
}
发现在这个类中,会初始化一个静态代码块,其中有一个Integer类型的cache数组,并且缓存了K个Integer对象。而当Integer与int相比较的时候,反编译得到的是:t1.intValue() = t2;
再看看intValue():
public int intValue() {
return value;
}
返回的是public Integer(int value) {
this.value = value;
}
构造函数带入的int值。
所以,我们知道了在-128~127之间的数相比较返回都应该为true,t4因为是新创建的对象,在Integer缓存中找不着,与缓存中的Integer对象进行比较所以为false。