Java常量池詳解之Integer緩存


一個Java question,求輸出結果
 
public class IntegerTest {
	public static void main(String[] args) {
		objPoolTest();
	}

	public static void objPoolTest() {
		Integer i1 = 40;
		Integer i2 = 40;
		Integer i3 = 0;
		Integer i4 = new Integer(40);
		Integer i5 = new Integer(40);
		Integer i6 = new Integer(0);

		System.out.println("i1=i2 \t" + (i1 == i2));
		System.out.println("i1=i2+i3 \t" + (i1 == i2 + i3));
		System.out.println("i4=i5 \t" + (i4 == i5));
		System.out.println("i4=i5+i6 \t" + (i4 == i5 + i6));

		System.out.println();
	}
}
 

輸出結果是

 

i1=i2 	true
i1=i2+i3 	true
i4=i5 	false
i4=i5+i6 	true
看起來比較Easy的問題,但是Console輸出的Result和我們所想的確恰恰相反,我們就疑惑了,這是為什么咧?
最后通過網上搜索得知Java為了提高性能提供了和String類一樣的對象池機制,當然Java的八種基本類型的包裝類(Packaging Type)也有對象池機制。

Integer i1=40;Java在編譯的時候會執行將代碼封裝成Integer i1=Integer.valueOf(40);通過查看Source Code發現
   /**
     * Returns a <tt>Integer</tt> instance representing the specified
     * <tt>int</tt> value.
     * If a new <tt>Integer</tt> instance is not required, this method
     * should generally be used in preference to the constructor
     * {@link #Integer(int)}, as this method is likely to yield
     * significantly better space and time performance by caching
     * frequently requested values.
     *
     * @param  i an <code>int</code> value.
     * @return a <tt>Integer</tt> instance representing <tt>i</tt>.
     * @since  1.5
     */
    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);
    }

 

Integer.valueOf()中有個內部類IntegerCache(類似於一個常量數組,也叫對象池),它維護了一個Integer數組cache,長度為(128+127+1)=256;Integer類中還有一個Static Block(靜態塊)
static {
        for(int i = 0; i < cache.length; i++)
        cache[i] = new Integer(i - 128);
    }

 

從這個靜態塊可以看出,Integer已經默認創建了數值【-128-127】的Integer緩存數據。所以使用Integer i1=40時,JVM會直接在該在對象池找到該值的引用。   也就是說這種方式聲明一個Integer對象時,JVM首先會在Integer對象的緩存池中查找有木有值為40的對象,如果有直接返回該對象的引用;如果沒有,則使用New keyword創建一個對象,並返回該對象的引用地址。因為Java中【==】比較的是兩個對象是否是同一個引用(即比較內存地址),i2和i2都是引用的同一個對象,So i1==i2結果為”true“;而使用new方式創建的i4=new Integer(40)、i5=new Integer(40),雖然他們的值相等,但是每次都會重新Create新的Integer對象,不會被放入到對象池中,所以他們不是同一個引用,輸出false。



  對於i1==i2+i3、i4==i5+i6結果為True,是因為,Java的數學計算是在內存棧里操作的,Java會對i5、i6進行拆箱操作,其實比較的是基本類型(40=40+0),他們的值相同,因此結果為True。
  

  好了,我想說道這里大家應該都會對Integer對象池有了更進一步的了解了吧,我在諾諾的問一句如果把40改為400猜猜會輸出什么?
 
i1=i2 	false
i1=i2+i3 	true
i4=i5 	false
i4=i5+i6 	true
這是因為Integer i1=400,Integer i2=400他們的值已經超出了常量池的范圍,JVM會對i1和i2各自創建新的對象(即Integer i1=new Integer(400)),所以他們不是同一個引用。
 
 
轉載自:http://www.tuicool.com/articles/aqyaYnm


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM