HelloWorld 善戰(zhàn)者,求之于勢,不責于人;故能擇人而任勢。

          知止而后有定,定而后能靜,靜而后能安,安而后能慮,慮而后能得。物有本末,事有終始。知所先后,則近道矣。

            BlogJava :: 首頁 ::  :: 聯(lián)系 ::  :: 管理 ::
            167 隨筆 :: 1 文章 :: 40 評論 :: 0 Trackbacks
          package com.test;
          public class 解包裝包 {
             public static void main(String []args) {
               Integer a = 100;
               Integer b = 100;
               System.out.println(a==b);
             }
          }
          打印結(jié)果為:true
          但是如果換成 128 > var >= -128 之外的整數(shù)就打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];
          }
          return new Integer(i);
          }
          。。。

          。。。
          private static class IntegerCache {
          private IntegerCache(){}
          static final Integer cache[] = new Integer[-(-128) + 127 + 1];
          static {
          for(int i = 0; i < cache.length; i++)
          cache
          = new Integer(i - 128);
          }
          }
          。。。
          這邊是java為了提高效率,初始化了-128--127之間的整數(shù)對象
          所以在賦值在這個范圍內(nèi)都是同一個對象。

          再加一句
          Integer a = 100;
          a++;
          //這邊a++是新創(chuàng)建了一個對象,不是以前的對象。
              public static void main(String []args) {
                  Integer a = 100;
                  Integer b = a;
                  a++;
                  System.out.println(a==b);
              }
          打印就是false

          對于127--128沒有多大關(guān)系,但是在這范圍之外就影響性能了吧,就像StringBuffer VS String一樣了


          </script>

          posted on 2007-08-13 18:50 helloworld2008 閱讀(2881) 評論(0)  編輯  收藏 所屬分類: java
          主站蜘蛛池模板: 天峨县| 开平市| 弋阳县| 丹巴县| 巴楚县| 乌什县| 泸水县| 霍林郭勒市| 巴彦县| 黑河市| 祥云县| 玉田县| 得荣县| 宜良县| 青田县| 修文县| 潢川县| 会泽县| 平原县| 东港市| 娄烦县| 吉木萨尔县| 灵宝市| 钟山县| 鄂尔多斯市| 久治县| 宣化县| 金华市| 米脂县| 丰城市| 万荣县| 宁乡县| 达孜县| 元朗区| 龙井市| 威远县| 裕民县| 历史| 云和县| 安图县| 顺昌县|