我的一畝三分地

            BlogJava :: 首頁 :: 新隨筆 :: 聯系 :: 聚合  :: 管理 ::
            2 隨筆 :: 14 文章 :: 3 評論 :: 0 Trackbacks

          下面是李sir發給我的
          Integer j1 = 127;
          Integer j2 = 127;
          System.out.println( j1==j2); //True

          Integer k1 = 128;
          Integer k2 = 128;
          System.out.println( k1==k2); //False

          Integer w1 = -128;
          Integer w2 = -128;
          System.out.println( w1==w2); //True

          Integer m1 = -129;
          Integer m2 = -129;
          System.out.println( m1==m2); //False

          I've seen a lot of posts in this thread about what is happening on ==

          It's simple:

          When we do
          ??????? Integer i = 127;
          autoboxing turns this into:
          ??????? Integer i = Integer.valueOf( 127 );

          Go look at the implementation of Integer.valueOf(), and you'll find:
          ??? 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);
          ??? }

          If the int value is between -128 and 127, it will return a cached Integer value. This way we avoid creating many duplicate Integer objects for those common values. It save's on memory and improves performance.

          And, of course, it does mean that Integer i = 127 will always return the same Integer instance.?

          再聯想到以前討論的String問題,
          ??????????????? String a = new String("Hello World");
          ? ? ? ? ? ? ? ? String b = "Hello World";
          ? ? ? ? ? ? ? ? String c ="Hello World";
          這里創建了幾個對象,a==b么?b==c么?

          這里只創建了兩個新對象,一個是“Hello World”對象,另一個是與“Hello World”有相同值的對象。a b c都是對象引用。其中a==b為fasle,因為a b指向不同的對象,b==c為true,這是因為b c都指向同一個對象。因為String是一個不可變的對象,而String的直接量賦值會自動尋找以前生成了的內容相同的實例賦給引用,若以前沒有內容相同的實例存在,則創建新實例。故會發生b==c。

          posted on 2006-12-06 15:15 王某某 閱讀(216) 評論(0)  編輯  收藏 所屬分類: Java基礎
          主站蜘蛛池模板: 自治县| 醴陵市| 平山县| 雷山县| 西华县| 南郑县| 柯坪县| 固原市| 五华县| 五莲县| 隆回县| 锡林郭勒盟| 五原县| 石景山区| 化隆| 涟源市| 襄垣县| 修武县| 海阳市| 建水县| 建昌县| 夏津县| 都匀市| 文化| 广宁县| 宕昌县| 娱乐| 玉树县| 琼结县| 四川省| 筠连县| 聊城市| 盘山县| 久治县| 峨眉山市| 赤壁市| 临清市| 三江| 泸定县| 盐城市| 潞西市|