為什麼Java中1000==1000為false而100==100為true?

來源:互聯網
上載者:User

為什麼Java中1000==1000為false而100==100為true?

這是一個挺有意思的討論話題。

如果你運行下面的代碼

  1. Integer a = 1000, b = 1000;  
  2.     System.out.println(a == b);//1 
  3.     Integer c = 100, d = 100;  
  4.     System.out.println(c == d);//2 

你會得到

false
true

基本知識:我們知道,如果兩個引用指向同一個對象,用==表示它們是相等的。如果兩個引用指向不同的對象,用==表示它們是不相等的,即使它們的內容相同。

因此,後面一條語句也應該是false 。

這就是它有趣的地方了。如果你看去看 Integer.java 類,你會發現有一個內部私人類,IntegerCache.java,它緩衝了從-128到127之間的所有的整數對象。

所以事情就成了,所有的小整數在內部緩衝,然後當我們聲明類似——

  1. Integer c = 100; 

的時候,它實際上在內部做的是

  1. Integer i = Integer.valueOf(100); 

現在,如果我們去看valueOf()方法,我們可以看到

  1. public static Integer valueOf(int i) { 
  2.       if (i >= IntegerCache.low && i 
  3.           return IntegerCache.cache[i + (-IntegerCache.low)]; 
  4.       return new Integer(i); 
  5.     } 

如果值的範圍在-128到127之間,它就從快取返回執行個體。

所以…

  1. Integer c = 100, d = 100; 

指向了同一個對象。

這就是為什麼我們寫

  1. System.out.println(c == d); 

我們可以得到true。

現在你可能會問,為什麼這裡需要緩衝?

合乎邏輯的理由是,在此範圍內的“小”整數使用率比大整數要高,因此,使用相同的底層對象是有價值的,可以減少潛在的記憶體佔用。

然而,通過反射API你會誤用此功能。

運行下面的代碼,享受它的魅力吧

  1. public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException { 
  2.  
  3.       Class cache = Integer.class.getDeclaredClasses()[0]; //1 
  4.       Field myCache = cache.getDeclaredField("cache"); //2 
  5.       myCache.setAccessible(true);//3 
  6.  
  7.       Integer[] newCache = (Integer[]) myCache.get(cache); //4 
  8.       newCache[132] = newCache[133]; //5 
  9.  
  10.       int a = 2; 
  11.       int b = a + a; 
  12.       System.out.printf("%d + %d = %d", a, a, b); // 
  13.     } 

譯文連結:http://www.codeceo.com/article/why-java-1000-100.html
英文原文:Why 1000 == 1000 Returns False, but 100 == 100 Returns True in Java?

聯繫我們

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