面試例子:
public static void main(String arg[]){ Integer a=3; Integer b=3; System.out.println(a==b); System.out.println(a.equals(b)); a=3333; b=3333; System.out.println(a==b); System.out.println(a.equals(b)); }
此程式列印出來的結果分別為:true,true,false,true。那麼為什麼會出現這種結果呢。 原因分析
我們要知道當給一個Integer對象賦一個int值時,Integer的valueOf方法會被調用。那麼,我們看看Integer的valueOf方法到底做了些什麼。源碼如下:
代碼一:
public static Integer valueOf(int i) { assert IntegerCache.high >= 127; if (i >= IntegerCache.low && i <= IntegerCache.high) return IntegerCache.cache[i + (-IntegerCache.low)]; return new Integer(i);}
代碼二:
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) { 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); } 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() {}}
通過代碼一我們可以看出,當valueOf傳入的值在IntegerCache.low和IntegerCache.high之間時,Integer被賦的值將從IntegerCache.cache數組中獲得,也就是通過緩衝中獲得。
再看代碼二,IntegerCache.low為常量-128。而IntegerCache.high如果在啟動JVM時沒有指定-XX:AutoBoxCacheMax參數,預設為127。綜合兩段代碼,我們可以知道,在預設情況下,在-128到127之間的資料在賦值時會從緩衝中獲得。 結論
因此,在-128到127之間的資料多次獲得的均為同一個對象,而超出這個範圍的資料將會建立一個新的對象,只能通過equals方法比較的才是對象的值。