先看一小段源码:
Integer a1=100; Integer a2=100; Integer b1=new Integer(100); Integer b2=new Integer(100); Integer c1=128; Integer c2=128; System.out.println(a1==a2); System.out.println(b1==b2); System.out.println(c1==c2);
输出结果:true false,false;
首先b1==b2这个肯定是false,通过关键字new出来的地址存储在堆区并且地址是不同的,所以引用也不会相同
关键是a和c都是直接赋值,为什么结果不一样呢?
这是因为Integer作为int的包装类,它能对一定范围类的数据有缓存.(通过查看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) { 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() {} }
这个具体的范围可知为:-128-127
然后直接赋值的时候,会内部调用Integer的valueof(int)的方法
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)方法,若数值在-128-127之间,直接从缓存cache中读取,若是不在,直接通过new操作符创建