我的一畝三分地

            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 王某某 閱讀(215) 評論(0)  編輯  收藏 所屬分類: Java基礎
          主站蜘蛛池模板: 英德市| 马边| 扎鲁特旗| 女性| 石泉县| 新乡县| 普定县| 刚察县| 密山市| 莆田市| 科尔| SHOW| 中超| 黎平县| 湘乡市| 威信县| 上林县| 达州市| 镇江市| 兴安盟| 广宗县| 故城县| 德钦县| 民县| 沂水县| 蛟河市| 元阳县| 龙游县| 贵阳市| 乌拉特前旗| 陕西省| 鹤岗市| 中江县| 合水县| 宣武区| 五河县| 民权县| 德江县| 安顺市| 比如县| 潼南县|