Integer自動裝拆箱

來源:互聯網
上載者:User

標籤:style   blog   color   for   代碼   div   

public static void main(String[] args) {    Integer a1 = 1;    Integer a2 = 1;    Integer b1 = 127;    Integer b2 = 127;    Integer c1 = 128;    Integer c2 = 128;    Integer d1 = 321;    Integer d2 = 321;    System.out.println(a1 == a2);    System.out.println(b1 == b2);    System.out.println(c1 == c2);    System.out.println(d1 == d2);}

結果:

true
true
false
false

原因:

首先我們來看一下JDK源碼是如何?Integer.valueOf()方法的;

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);}

其中IntegerCache是Integer類中的一個內部類,其代碼比較簡單,如下所示:

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);    }}

如果傳入的int在[-128~127],那就嘗試看前面的緩衝中有沒有打過包的相同的值,如果有就直接返回,否則就建立一個Integer執行個體。

看到這兒之後,上面的結果就顯而易見了。

 

 

 

 

 

 

 

 

 

 

 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.