关于Integer的缓存问题

先看一段示例代码:

public class TestMain {
    public static void main(String[] args) {
        Integer a = 66;
        Integer b = 66;
        System.out.println("a等于b:" + (a == b));//结果是true
        Integer c = 166;
        Integer d = 166;
        System.out.println("c等于d:" + (c == d));//结果是false
    }
}

为什么会是这样的结果,以上代码看上去只是单纯的赋值,所以我们反汇编看下,底层是否有调用什么方法,而我们却不知道。
在这里插入图片描述
以上是部分反汇编后的代码,可以看到反汇编的第一行的66,和我们代码第三行对应,反汇编的第二行则调用的是Integer.valueOf()的方法,对66这个数字进行自动装箱。从这里也可以猜到自动装箱和拆箱在底层是怎么实现的了,其实最后还是调用相应方法来做类型的转换。

所以接下来看Integer.valueOf()方法的源码:

public static Integer valueOf(int i) {
         //这里做了一个比较,如果在这个范围内的数值,则取IntegerCache里的值,否则新建Integer对象
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

接着再看下IntegerCache是什么?

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

发现它是一个静态内部类,它的low值默认是-128,high值会先在静态块里初始化为127,但是如果我们有通过虚拟机的参数来调整high的值,那么最后high值就会被赋值成我们设置的值,然后会把low~high范围内的值都添加到一个数组cache[]里。

这里用的是默认值127,所以cache[]的范围是-128~127。

返回来再看看valueOf()方法,拿66做个示例:

public static Integer valueOf(int i) {
         //这里做了一个比较,如果在这个范围内的数值,则取IntegerCache里的值,否则新建Integer对象
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

因为66在-128~127范围内,所以走的是IntegerCache.cache[i + (-IntegerCache.low)]的逻辑,所以代入具体数值的话是这样的:IntegerCache.cache[66 + (128)]=IntegerCache.cache[194],这表示的是cache[]数组的第194位。要知道,这个数组的第0个下标的数值是-128,之后每个下标数字加一,所以第194个下标的数值就是等于66。所以返回了已经在数组cache[]里的66这个Integer类型值。

a和b相等

a和b会相等,是因为他们的值都是来自cache[]数组的第194下标,引用指向同一个位置。

c和d不相等

c和d不相等,是因为数值不在cache[]数组范围内,cache[]数组给不了自己要的值,就都只能去新建对象了,所以导致c和d引用指向不同的内存地址,自然也就不相等了。

这样的话只要值是在-128~127范围内的Integer类型,都会去取cache[]数组里的值么?

肯定是不会的,要知道如果是new Integer()的话,直接就会在堆中创建对象,而不会去cache[]数组里取值了,不信可以看下new Integer()反汇编的结果。
实例代码如下:

public class TestMain {
    public static void main(String[] args) {
        Integer a = new Integer(66);
        Integer b = 66;
        System.out.println("a等于b:" + (a == b));//结果是false
    }

反汇编如下:
在这里插入图片描述
可以看到第一个66调用的是Integer的构造方法,而第二个66才是使用的Integer.valueOf(),他们指向的内存地址不同,输出结果自然是false。

总结

Integer在-128~127(该数值可调整)范围内的,只要没有new对象,都会去取已经缓存在cache[]数组里的值,所以在这范围内的Integer类型的引用都会指向同一地址,是相等的。而不在这范围内的Integer类型的变量,则会自己去新建一个Integer对象,所以不在这范围内的Integer类型是不等的。

发布了168 篇原创文章 · 获赞 158 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_38106322/article/details/104253574