HelloWorld 善戰者,求之于勢,不責于人;故能擇人而任勢。

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

            BlogJava :: 首頁 ::  :: 聯系 ::  :: 管理 ::
            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);
             }
          }
          打印結果為:true
          但是如果換成 128 > var >= -128 之外的整數就打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之間的整數對象
          所以在賦值在這個范圍內都是同一個對象。

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

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


          </script>

          posted on 2007-08-13 18:50 helloworld2008 閱讀(2881) 評論(0)  編輯  收藏 所屬分類: java
          主站蜘蛛池模板: 丘北县| 婺源县| 乐安县| 兴仁县| 德江县| 峡江县| 碌曲县| 潢川县| 南溪县| 达州市| 孟村| 马边| 碌曲县| 贵南县| 牟定县| 西宁市| 镇远县| 湘潭县| 丁青县| 永新县| 永宁县| 保靖县| 托克托县| 家居| 从化市| 扬州市| 金川县| 延吉市| 楚雄市| 灯塔市| 增城市| 卢龙县| 平湖市| 隆昌县| 台湾省| 武城县| 丹棱县| 澜沧| 乌兰察布市| 延川县| 银川市|