如果運(yùn)行如下代碼
Integer a = 1000, b = 1000;
System.out.println(a == b);
Integer c = 100, d = 100;
System.out.println(c == d);
你會(huì)得到下面的結(jié)果
false
true
我們知道 == 比較的是引用指向的對(duì)象是否相同,內(nèi)存地址是否一樣。如果查看Integer的代碼就會(huì)發(fā)現(xiàn)當(dāng)你聲明Integer a = 100;
實(shí)際上,運(yùn)行的是Integer a = Integer.valueOf(100))
,繼續(xù)查看ValueOf函數(shù)
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
如果值在-128到127之間,它就會(huì)返回該緩存的實(shí)例。至此就明白了以上問題。下面就是個(gè)很有趣的例子.
Class cache = Integer.class.getDeclaredClasses()[0];
Field myCache = cache.getDeclaredField("cache");
myCache.setAccessible(true);
Integer[] newCache = (Integer[]) myCache.get(cache);
newCache[132] = newCache[133];
int a = 2;
int b = a + a;
System.out.printf("%d + %d = %d", a, a, b);