JAVA Integer值的範圍

來源:互聯網
上載者:User

標籤:baidu   blog   --   off   ret   eof   final   test   nal   

原文出處:http://hi.baidu.com/eduask%C9%BD%C8%AA/blog/item/227bf4d81c71ebf538012f53.html

package com.test;public class Test {   public static void main(String []args) {     Integer a = 100;//此處若使用new,則==值必為false     Integer b = 100;     System.out.println(a==b);//true     Integer c = 150;     Integer d = 150;     System.out.println(c==d);//false   }}

 

  這是什麼原因呢?
  1。java在編譯的時候 Integer a = 100; 被翻譯成-> Integer a = Integer.valueOf(100);
  2。比較的時候仍然是對象的比較
  3。在jdk源碼中

public static Integer valueOf(int i) {   final int offset = 128;   if (i >= -128 && i <= 127) { // must cache   return IntegerCache.cache[i + offset]; //符合值範圍時候,進入也建立好的靜態IntergerCache,i+offset的值表示去取cache數組中那個下標的值  }   return new Integer(i); //當不符合-128 127值範圍時候。記住用的:new,開闢新的記憶體空間,不屬於IntergerCache管理區} 

  而

private static class IntegerCache {   private IntegerCache(){}   static final Integer cache[] = new Integer[-(-128) + 127 + 1]; //開闢-128到127的記憶體區。有0的位置哦  static {     for(int i = 0; i < cache.length; i++)       cache[i] = new Integer(i - 128); //為記憶體區的數組每個對象賦值    }   } 

  這邊是java為了提高效率,初始化了-128--127之間的整數對象,所以在賦值在這個範圍內都是同一個對象。

  

  再加一句
  Integer a = 100;
  a++;
  //這邊a++是新建立了一個對象,不是以前的對象。

    public static void main(String []args) {        Integer a = 100;        Integer b = a;//此時b指標指向值為100的堆地址  即a的堆地址,a==b成立        a++;//此時a指向的值發生變化為101,a指標指向101的堆地址。而b任然指向100        System.out.println(a==b);//false    }

 

 


 

JAVA 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.