1. 程式人生 > >Integer自動裝箱和拆箱和比較

Integer自動裝箱和拆箱和比較

一、int Integer比較。不管Integer是直接等於一個數值,還是=new Integer(xxx);都是Integer拆箱成int,再去和前面那個int數值比較。

二、IntegerInteger比較,存在三種情況。

a.它們兩個都是直接等於一個數值,

那麼看這個數值大小,-128~127之間,會轉成Integer.valueOf(xxx),寫入快取,第二次寫入就是用快取中的值,所以比較是true

如果是-128~127之外,就會轉成new Integer(xxx),它們就是引用的比較。

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) {
            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;

        cache = new Integer[(high - low) + 1];
        int j = low;
        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() {}
}

b.一個等於數值,一個等於new Integer,對於newInteger,引用是指向堆,對於這個等於數值的那個,是指向常量池,它們記憶體地址不一樣,所以比較就是false

c.兩個都等於new Integer==也不會相等。同上。