public class Test {
public static void main(String[] args) {
int a = 1;
int b = 1;
Integer c = 3;
Integer d = 3;
Integer e = 321;
Integer f = 321;
System.out.println(a == b);
System.out.println(c == d);
System.out.println(e == f);
}
}
output:
true
true
false
看到这个结果,一定非常的奇怪,为什么会出现这种情况。
原因就在Integer的方法 valueOf()方法。
public static Integer valueOf(int i) {
if(i >= -128 && i <= IntegerCache.high)
return IntegerCache.cache[i + 128];
else
return new Integer(i);
}
private static class IntegerCache {
static final int high;
static final Integer cache[];
static {
final int low = -128;
// high value may be configured by property
int h = 127;
if (integerCacheHighPropValue != null) {
// Use Long.decode here to avoid invoking methods that
// require Integer's autoboxing cache to be initialized
int i = Long.decode(integerCacheHighPropValue).intValue();
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里弄了一个缓存,对于在 -128—127 之间的数值,会直接使用该缓存里的对象
也就是说 Integer c = 3 或者 Integer c = Integer.valueOf(3) ,最终 c 得到的是Integer里的缓存对象
同理,d也是获得该相同对象因此 进行 c == d 比较时,c和d引用的是同一个对象,因此就true
而对于321,已经超出缓存范围了,因此 valueOf 方法会生成一个新的Integer对象因此e和f就引用不同 的对象了,进行==比较,当然就false了
另外,对Integer的缓存,我们在日常开发时,对于小的整型值应该充分利用Integer的缓存对象省去过多的对象创建,回收的操作,这样会极大的提高程序性能 。
所以如果想比较连个Integer 对象的值是否相等,可以equals()或者compareTo(),或者intValue()去比较。
参考文章:http://blog.youkuaiyun.com/zhoumingp/article/details/8298566