public static void main(String[] args) {
Integer a = 1000,b=1000;
System.out.println(a == b); //false
Integer c = 100,d=100;
System.out.println(c == d); //true
}
}
如果把==換成equals,那麼結果都是true
基本知識:如果兩個引用對象指向同一個對象,用==表示他們是相等的。如果兩個引用指向不同的對象,用==表示他們是不相等,即使他們的內容相同。
原因分析:在Integer類中有一個內部私有類IntegerCache,它的緩存是從-128-127之間的所有整數對象。---->就說明所有的小整數在內部緩存。
所以:Integer c = 100 等價於Integer c =Integer.valueOf(100)
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
如數值的範圍在-128-127之間都是從高速緩存返回實例的。---所以指向同一個對象。
那麼爲什麼需要緩存呢?
因爲此範圍內的整數的使用率比較高。使用相同的底層對象是有代價的,可以減少潛在的內存佔用。