奇怪的Java題:為什麼1000 == 1000返回為False,而100 == 100會返回為True?

來源:互聯網
上載者:User

標籤:syntax   nbsp   int   pad   就會   keyword   記憶體最佳化   數值   declare   

如果你運行如下代碼:

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

你會得到以下運行結果:

12 falsetrue

我們知道,如果兩個引用指向同一個對象,那麼==就成立;反之,如果兩個引用指向的不是同一個對象,那麼==就不成立,即便兩個引用的內容是一樣的。因此,結果就會出現false。

這是非常有趣的地方。如果你查看Integer.java類,你會找到IntegerCache.java這個內部私人類,它為-128到127之間的所有整數對象提供緩衝。

這個東西為那些數值比較小的整數提供內部緩衝,當進行如此聲明時:

1 Integer c = 100;

它的內部就是這樣的:

1 Integer i = Integer.valueOf(100);

如果我們觀察valueOf()類函數,我們可以看到

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

如果值在-128到127之間,它就會返回該緩衝的執行個體。

因此。。。

1 Integer c = 100, d = 100;

兩者指向同樣的對象。

這就是為什麼這段代碼的結果為true了:

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

現在你可能會問,為什麼會為-128到127之間的所有整數設定緩衝?

這是因為在這個範圍內的小數值整數在日常生活中的使用頻率要比其它的大得多,多次使用相同的底層對象這一特性可以通過該設定進行有效記憶體最佳化。你可以使用reflection API任意使用這個功能。

運行下面的這段代碼,你就會明白它的神奇所在了。

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

奇怪的Java題:為什麼1000 == 1000返回為False,而100 == 100會返回為True?

聯繫我們

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