首先先以以下代码来开始文章的主题:
public static void main(String[] args) {
Integer a = 1;
Integer b = 1;
System.out.println(a==b);
}
以上代码输出的结果是true
而将上述代码改成如下:
public static void main(String[] args) {
Integer a = 1000;
Integer b = 1000;
System.out.println(a==b);
}
则输出的结果是false。
可能有些人对上述的答案有点迷糊。那我具体的给大家分析以下这个问题。
第一类人应该是认为两个都是true,因为a和b的值都是相等的所以他们以为都应该为true,如果是这种想法那可能要再去好好学学java基础了。
第二类人认为两个都是false,因为a和b的类型是包装类型Integer,而Integer属于对象类型就是引用类型,==比较的是内存地址所以即使数值相等但是他们的内存地址是不同的,所以认为两个答案都是false,其实回答两个都是false的人java基础应该可以,至少知道什么是引用类型了,只不过是知识面窄了一点,平时对java内部的源码看的少了一点,现在我带大家来分析这个问题。
首先a和b都是引用类型,原则上讲结果都应该是false但是第一个输出的结果是true那肯定是JDK里的猫腻了,切入正题付源码:
在Integer类的内部有如下内部类:
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) -1);
}
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() {}
}
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);
}
以上代码的作用大致就是缓存Integer对象。从-128到127之间的值Integer用缓存机制,只创建一次对象然后放cache[]中缓存,当下一次要用到该对象时则直接从数组中取出,这就导致了为什么第一次的结果为true的原因。