Integer類型值相等或不等分析,integer不等

來源:互聯網
上載者:User

Integer類型值相等或不等分析,integer不等

     看到部落格園一位博友寫的面試問題,其中一題是 Integer a = 1; Integer b = 1 ; (a == b)?true :false; 當時我一看,這不是明顯的true 嘛,  看到評論討論才知道,對於Integer值比較 有範圍規定   。平時都是用equals做比較判斷,簡單省事。沒注意到這些細節。正好趁此機會好好Google了一下,以此做個備份。

     用以下代碼做測試

 

 1      @Test 2     public void testInteger() { 3         Integer a = -129; 4         Integer a1 = -129; 5         Integer aaa = new Integer(-129); 6  7         Integer aa = -128; 8         Integer aa1 = -128; 9 10         System.out.println("a==a1:" + (a == a1) + "--aa==aa1:" + (aa == aa1)); //   a==a1:false--aa==aa1:true11         System.out.println("aaa==a1:" + (aaa == a1));        // aaa==a1:false12         System.out.println("a.equals(a1):" + a.equals(a1));   //  a.equals(a1):true13 14         Integer b = 128;15         Integer b1 = 128;16         System.out.println("b==b1:" + (b == b1));    // b==b1:false17         System.out.println("b.equals(b1):" + b.equals(b1));  //  b.equals(b1):true18 19         Integer c = 127;20         Integer cc = 127;21         Integer d = 1;22         Integer dd = 1;23 24         System.out.println("c==cc:" + (c == cc) + "----d==dd:" + (d == dd));  // c==cc:true----d==dd:true25         System.out.println("------------");26 27         Integer e = 128;28         int e1 = 128;29         System.out.println("e == e1:" + (e == e1));  // e == e1:true30     }

      得出的結論是  Integer 類型的值在[-128,127] 期間,Integer 用 “==”是可以的。  為什麼會出現這個情況呢,實際上在我們用Integer a = 數字;來賦值的時候Integer這個類是調用的public static Integer valueOf(int i)這個方法。

     

     

     

 

 

        我們來看看ValueOf(int i)的代碼,可以發現他對傳入參數i做了一個if判斷。在-128<=i<=127的時候是直接用的int未經處理資料類型,而超出了這個範圍則是new了一個對象。我們知道"=="符號在比較對象的時候是比較的記憶體位址,而對於未經處理資料類型是直接比對的資料值。那麼這個問題就解決了。

       還有一點需要注意到 是   Integer e = 128; int e1 = 128;  e == e1:true  而  Integer b = 128; Integer b1 = 128;   b==b1:false   ,e=128 已經大於127了,所以e 是一個對象(new 出來的) 為什麼e = e1 是ture , 因為  int為實值型別,參考型別Integer與實值型別int比較顯然比較的是值因為int在堆中是不開闢記憶體的,他在棧中的值則為他本身的值所以e==e1比較的是他們各自的value, e==e1為true

     總結:Integer 類型的值在[-128,127] 期間,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.