Integer常量池

在Java中有一个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 (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() {}
    }

我们可以看到,Integer一个变量的时候不需要new而是将对象放到了常量池中。他的数值范围是###-128~127
所以我们这样写

Integer a = 10;

而不是

new Integer (int 10);

如下面试题:

public class test {
    public static void main(String[] args){
        Integer a = 1;
        Integer b = 2;
        Integer c = 3;
        Integer d = 3;
        Integer e = 300;
        Integer f = 300;
        Long g = 3L;
        Long h =2L;
        System.out.println(c ==d);//比较地址值,在范围内
        System.out.println(e ==f);//比较地址值,在范围外
        System.out.println(c ==(a+b));//比较数值
        System.out.println(c.equals(a+b));//比较数值
        System.out.println(g ==(a+b));//比较数值
        System.out.println(g.equals(a+b));//Long的equals()方法会校验Long类型
        System.out.println(g.equals(a+h));//比较数值
    }
}
结果
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。