java源碼學習2-Integer



1、Integer的內部靜態類IntegerCache

private static class IntegerCache {
        static final int low = -128;
        static final int high;
        static final Integer cache[];

        static {
            // high value may be configured by property
            int h = 127;
            String integerCacheHighPropValue =
                sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
            if (integerCacheHighPropValue != null) {
                int i = parseInt(integerCacheHighPropValue);
                i = Math.max(i, 127);
                // Maximum array size is Integer.MAX_VALUE
                h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
            }
            high = h;

            cache = new Integer[(high - low) + 1];
            int j = low;
            for(int k = 0; k < cache.length; k++)
                cache[k] = new Integer(j++);
        }

        private IntegerCache() {}
    }
該靜態類實現的內容主要是講-128~127折256個數字放在cache[]  這個數組當中,起到一個快速使用的目的。


2、看Integer的valueOf方法 參數 是 int  類型

public static Integer valueOf(int i) {
        assert IntegerCache.high >= 127;
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }
從這裏可以看出  如果i的值 不在IntegerCache的cache數組內,則就會新建一個Integer對象

考題:

                Integer a=new Integer(3);
		Integer b=3;
		int c=3;
		Integer d=new Integer(3);
		Integer e=Integer.valueOf(3);
		Integer f=Integer.valueOf(3);
		Integer g=Integer.valueOf(300);
		Integer h=Integer.valueOf(300);
		System.out.println(a==b);//false,都是Integer對象,指向的引用不同
		System.out.println(a==c);//true,a自動拆箱成int,比較數據都是3
		System.out.println(a==d);//false,同樣比較的是對象引用
		System.out.println(a==e);//false,比較的對象引用,不過e的對象引用與內部類IntegerCache有關
		System.out.println(e==f);//true指向的都是IntegerCache 內部靜態類中的cache數組,
		System.out.println(g==h);//false,因爲300》127,所以調用Integer.valueof方法會生成新的Integer對象,所以是false


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