走近Java之包裝器類Integer

前幾天,有個同事問了我一個關於Integer類賦值的問題,頗有意思,咱們一塊兒來看一下(若是有說的不正確的地方,歡迎你們指正)。html

image
如上圖,一樣是賦值,可是兩次比較的結果徹底不一樣。咱們走近了解一下。
在Integer中,有一個靜態內部類IntegerCache,其內有一個Integer緩存數組,範圍從-128到127
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是處理VM入參,可忽略
        if (integerCacheHighPropValue != null) {
            try {
                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);
            } catch( NumberFormatException nfe) {
                // If the property cannot be parsed into an int, ignore it.
            }
        }
        high = h;
        //構造一個長度是256的Integer數組
        cache = new Integer[(high - low) + 1];
        int j = low;
        //遍歷賦值-128到127
        for(int k = 0; k < cache.length; k++)
            cache[k] = new Integer(j++);

        // range [-128, 127] must be interned (JLS7 5.1.7)
        assert IntegerCache.high >= 127;
    }

    private IntegerCache() {}
}

 

當執行賦值語句的時候,會調用Integer的valueOf方法,此方法會判斷入參大小,若是在-128到127之間,就直接返回cache數組中的值,不然纔會建立Integer對象。
image
 
再看另一個問題.爲何i的結果都是5.
image
Integer是不可變類。在Integer類中,value被定義爲final,每一次賦值方法返回的都是新的對象,而不是改變value的值。也是由於這個緣由,爲了提升性能,因此纔有cache的Integer數組。
image
 Java中的8個包裝器類,以及String,均是不可變類。
相關文章
相關標籤/搜索