Java記錄 -76- Integer cache緩衝
Integer cache緩衝下面有一個簡單的關於Integer的執行個體,但出乎預料的是其輸出結果:
public class IntegerTest2 { public static void main(String[] args){ Integer i1 = 100; Integer i2 = 100; System.out.println(i1 == i2); Integer i3 = 200; Integer i4 = 200; System.out.println(i3 == i4); }}
上面的執行個體輸出結果為:true 和 false這是為什麼呢?有點不可思議 ...下面我們通過查看Integer的原始碼來分析一下(像這種問題也只能通過原始碼來查看分析其原因);看Integer的valueOf方法,該方法是將int的轉變為Integer,但當int值大於-128並小於127時,其必須緩衝 must cache,並返回的是IntegerCache的cache數組中的值;我們在看IntegerCache,該類是Integer的一個內部類,它定義了一個靜態Integer類型的數組,並在靜態塊中將其迴圈初始化值;也就是說,我們利用Integer獲得的大於-128並小於127的對象是,返回的都是緩衝起來的對象,並沒有新產生對象。
public static Integer valueOf(int i) { final int offset = 128; if (i >= -128 && i <= 127) { // must cache return IntegerCache.cache[i + offset]; } return new Integer(i); } private static class IntegerCache { private IntegerCache(){} static final Integer cache[] = new Integer[-(-128) + 127 + 1]; static { for(int i = 0; i < cache.length; i++) cache[i] = new Integer(i - 128); } }
JDK的API文檔提示:public static Integer valueOf(int i)如果不需要新的 Integer 執行個體,則通常應優先使用該方法,而不是構造方法 Integer(int),因為該方法有可能通過緩衝經常請求的值而顯著提高空間和時間效能。