Integer中的缓存机制

先看一个示例:

public static void main(String[] args) {
        Integer a=127;
        Integer b=127;
        System.out.println(a==b);

        Integer c=128;
        Integer d=128;
        System.out.println(c==d);
    }

输出:

true
false

为什么明明都是同一个数字进行==比较,当数字等于127的时候,两个Integer类型的变量进行==比较是相同的,数字式128的时候就不同了呢?

首先我们需要明确==和equals方法的区别,==比较两个对象的地址是否相同,equals比较两个对象的值是否相同。

然后查看上面代码的字节码,发现 Integer a=128;这句代码调用了Integer的valueOf方法,等价于Integer.valueOf(128)。

我们查看这个方法的源码。

public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

可以看到这里引入了一个IntegerCache,点进这个IntegerCache。

private static class IntegerCache {
        static final int low = -128;
        static final int high;
        static final Integer[] cache;
        static Integer[] archivedCache;

        static {
            // high value may be configured by property
            int h = 127;
            String integerCacheHighPropValue =
                VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
            if (integerCacheHighPropValue != null) {
                try {
                    h = Math.max(parseInt(integerCacheHighPropValue), 127);
                    // Maximum array size is Integer.MAX_VALUE
                    h = Math.min(h, Integer.MAX_VALUE - (-low) -1);
                } catch( NumberFormatException nfe) {
                    // If the property cannot be parsed into an int, ignore it.
                }
            }
            high = h;

            // Load IntegerCache.archivedCache from archive, if possible
            CDS.initializeFromArchive(IntegerCache.class);
            int size = (high - low) + 1;

            // Use the archived cache if it exists and is large enough
            if (archivedCache == null || size > archivedCache.length) {
                Integer[] c = new Integer[size];
                int j = low;
                for(int i = 0; i < c.length; i++) {
                    c[i] = new Integer(j++);
                }
                archivedCache = c;
            }
            cache = archivedCache;
            // range [-128, 127] must be interned (JLS7 5.1.7)
            assert IntegerCache.high >= 127;
        }

        private IntegerCache() {}
    }

发现这是Integer中的一个静态内部类。

可以看出,Integer内部是缓存了一个[-128, 127]范围的,如果超过这个范围那么就调用构造函数去创建一个新对象new Integer(i)。

这么做的目的是为了提高效率,省去构造对象的开支,Integer缓存了-128~127之间的数,这个过程在类加载的时候就已经完成了,所以后面需要的时候直接拿的缓存中的对象。

所以这就解释了为什么a==b是true而c==d是fasle,当Integer值在[-128, 127]范围时,都是从缓存中拿的同一个对象,使用==比较地址自然相同,所以返回true;而当其值不在[-128, 127]范围时,新创建了一个对象,两个不同对象比较地址值不同,当然返回false。

所以一般对于引用数据类型的对象进行比较,我们一般就是用equals方法进行比较,如果是自定义的数据类型,一般需要重写equals方法和hashCode方法。

public static void main(String[] args) {
        Integer a= 127;
        Integer b= 127;
        System.out.println(a.equals(b));

        Integer c= 128;
        Integer d= 128;
        System.out.println(c.equals(d));
    }

输出

true
true

 

  • 16
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值