我的一畝三分地

            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 王某某 閱讀(219) 評論(0)  編輯  收藏 所屬分類: Java基礎
          主站蜘蛛池模板: 竹溪县| 舟曲县| 庄河市| 金寨县| 纳雍县| 舒兰市| 新野县| 广汉市| 游戏| 塔城市| 淳安县| 金湖县| 望江县| 右玉县| 兴和县| 浮山县| 本溪| 临夏县| 泽普县| 开江县| 漳州市| 天镇县| 普定县| 青阳县| 瑞安市| 永登县| 宁都县| 博乐市| 桐柏县| 古浪县| 璧山县| 鄱阳县| 南江县| 张家川| 永康市| 永兴县| 比如县| 汉沽区| 望都县| 静海县| 定兴县|