java整数型常量池

首先看一段代码:

  Integer a=127;
        Integer b=127;
        System.out.println(a==b);

        Integer x=128;
        Integer y=128;
        System.out.println(x==y);

输出结果是:

true
false

问题来了127和128只差一个数为啥输出结果就是不一样呢?
看一下Integer的源码那你就知道了
首先在源码里面有一个叫IntegerCache的内部类,里面的low和high也指明了Integer的范围是-128~127,具体的源码就不分析了。127在范围内,所以可以在常量池中直接引用他,而128超出了常量池的范围,每次都是new出来的128.所以地址肯定是不一样的。

 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;
        }

猜你喜欢

转载自blog.csdn.net/qq_42678668/article/details/113000885