Integer的緩衝

來源:互聯網
上載者:User

標籤:

根據Integer類得到Integer執行個體的方式:

Integer instance=new Integer(int value);

Integer instance=Integer.valueOf(int value);

第一種方式每次當然都會產生一個新的執行個體,但是第二種方式就不盡然:

 1 public static void main(String[]args) { 2         Integer i1=Integer.valueOf(127); 3         Integer i2=Integer.valueOf(127); 4         System.out.println(i1==i2); 5          6         Integer i3=Integer.valueOf(128); 7         Integer i4=Integer.valueOf(128); 8         System.out.println(i3==i4); 9         10         Integer i5=Integer.valueOf(-128);11         Integer i6=Integer.valueOf(-128);12         System.out.println(i5==i6);13         14         Integer i7=Integer.valueOf(-129);15         Integer i8=Integer.valueOf(-129);16         System.out.println(i7==i8);17 }
truefalsetruefalse

之所以會導致這種結果,是因為Integer類內部對value值為-128到127範圍[-128,127]的執行個體緩衝了下來。 

類似如下代碼:

 1 public class Test { 2     public static void main(String[]args) { 3         MyInteger i1=MyInteger.valueOf(10); 4         MyInteger i2=MyInteger.valueOf(10); 5         System.out.println(i1==i2); 6          7         MyInteger i3=MyInteger.valueOf(11); 8         MyInteger i4=MyInteger.valueOf(11); 9         System.out.println(i3==i4);10     }11 }12 13 class MyInteger {14     private final int value;15     public MyInteger(int value) {16         this.value=value;17     }18     public static MyInteger valueOf(int i) {19         MyInteger[]caches=MyInteger.MyIntegerCache.caches;20         if(i>=1&&i<=10) {21             return caches[i-1];22         }23         return new MyInteger(i);24     }25     26     static class MyIntegerCache {27         static MyInteger[]caches=new MyInteger[10];28         static {29             for(int i=0;i<10;i++) {30                 caches[i]=new MyInteger(i+1);31             }32         }33     }34 }

 

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.