技术干货Java 杂谈

用int还是用Integer?

2017-12-12  本文已影响628人  buguge

昨天例行code review时大家有讨论到int和Integer的比较和使用。 这里做个整理,发表一下个人的看法。

【int和Integer的区别】

【各自的应用场景】

【附:Integer类的内部类IntegerCache和valueOf方法代码】

public final class Integer extends Number implements Comparable<Integer> {

    //。。。。。。。。。。。。

    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() {}
    }

    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);
    }
    
    //。。。。。。。。。。。。。

}
上一篇 下一篇

猜你喜欢

热点阅读