public static void main(String[] args) {
Integer a = 1000;
Integer b = 1000;
Integer c = 100;
Integer d = 100;
System.out.println("a == b is" + (a == b));
System.out.println("c == d is" + (c == d));
}
輸出結果:
a == b is false
c == d is true
由於Java的自動裝箱,a和b這兩個引用變量,指向的不是同一個堆內存地址。而使用==比較時,默認是比較兩者的內存地址是否相同,所以a和b用==來比較爲false
但爲什麼c和d用==比較,結果卻是true呢?在Java5中,在Interger的操作上引入了一個新功能來節省內存和提高性能。整型對象通過使用相同的對象引用實現了緩存和重用。
下面是java中java.util.Integer的部分源碼:
static {
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);
h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
} catch( NumberFormatException nfe) {
}
}
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]
assert IntegerCache.high >= 127;
}
適用於整數值區間-128至127。只適用於自動裝箱,並且使用構造函數創建對象不適合。