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);
             }
          }
          打印結果為: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沒有多大關系,但是在這范圍之外就影響性能了吧,就像StringBuffer VS String一樣了


          </script>

          posted on 2007-08-13 18:50 helloworld2008 閱讀(2878) 評論(0)  編輯  收藏 所屬分類: java
          主站蜘蛛池模板: 昆山市| 新巴尔虎右旗| 肥乡县| 广东省| 滦平县| 贡嘎县| 呼玛县| 米易县| 丰顺县| 大竹县| 南华县| 郴州市| 舒城县| 杨浦区| 满城县| 习水县| 桃源县| 陇西县| 郯城县| 晋城| 渑池县| 蒲江县| 报价| 丰镇市| 红安县| 元阳县| 房产| 昭觉县| 子洲县| 凤城市| 深圳市| 犍为县| 织金县| 皮山县| 高陵县| 溆浦县| 鹤峰县| 海门市| 天峻县| 金阳县| 上栗县|