Java記錄 -76- Integer cache緩衝

來源:互聯網
上載者:User

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),因為該方法有可能通過緩衝經常請求的值而顯著提高空間和時間效能。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.