首先我们来看一道关于Integer的题:
public class Test {
public static void main(String[] args) {
Integer a = 100;
Integer b = 100;
Integer c = 1000;
Integer d = 1000;
//引用类型"=="比较的是内存中的引用地址,不是比较数值的大小
System.out.println(a==b);//true
System.out.println(c==d);//false
}
}
为什么第一个输出的是true,第二个是false?
当我们执行 Integer a = 100;
的时候,实际上执行的是Integer a = Integer.valueOf(100);
究其原因,我们需要去看看Integer的源代码:
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
valueOf 方法会先判断 int i 的数值范围,通常情况下,IntegerCache.low=-128,IntegerCache.high=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++);
}
private IntegerCache() {}
}
不难看出,当 Integer 类被加载时,[-128,127] 中的所有数字都会保存在 Integer cache[ ] 数组中,这就是缓存区了;而且它是静态且 final 的,也避免了重复的实例化和垃圾回收。
当Integer的值在 [-128,127] 范围之内,都会去缓存区数组里边获取对应的Integer对象。
那么只要是同样的数值,拿到必然也是指向同一个缓存区的对象。
回到题目:
因为a和b都是100,符合缓存区的范围内,则拿到的是同一个Integer对象,使用 == 判断结果是true
而c和d都是1000,不符合缓存区的范围内,则分别产生了新的Integer对象,使用 == 判断,因为两者指向的不是同一个引用,最后结果就是false