java Integer.valueOf()方法

Integer.valueOf()方法實現如下:

  
    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()方法基於減少對象創建次數和節省內存的考慮,緩存了[-128,127]之間的數字。此數字範圍內傳參則直接返回緩存中的對象。在此之外,直接new出來。

IntegerCache的實現:

 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[i] = new Integer(i - 128);
	}
    }

測試代碼

        Integer i1 = Integer.valueOf(12);
        Integer i2 = Integer.valueOf(12);
        Integer i3 = Integer.valueOf(129);
        Integer i4 = Integer.valueOf(129);
        System.out.println(i1==i2);
        System.out.println(i3==i4);
        System.out.println(i1.equals(i2));
        System.out.println(i3.equals(i4));

打印結果如下:

true
false
true
true



發佈了125 篇原創文章 · 獲贊 50 · 訪問量 112萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章