128陷阱详解+源码分析

1、什么是128陷阱

请看下面的程序,注释为运行结果。

	Integer b = 127;
	Integer b1 = 127;
	System.out.println(b == b1);    //true
	
	Integer c = 128;
	Integer c1 = 128;
	System.out.println(c == c1);    //false

这就是128陷阱的形象实例。看完之后你是怎么理解的呢?
下面我们来说为什么会出现这种“差之毫厘,谬之千里"的现象:

2、为什么会出现128陷阱

首先对于 c==c1 返回false的原因还是很好理解的,因为Integer为int的包装类,所以创建c和c1时相当于创建了两个值相同的对象,而针对对象这种引用类型变量的 “==” 判断原理为:判断两个变量的地址是否相等,那么由于c和c1是Integer类创建的两个不同的对象,所以 c==c1 的结果为false。

那么b==b1为什么不是false呢,这就要从Integer b = 127;这行代码的底层原理讲起了。
在java5之后,引入了自动装箱和缓存机制,自动装箱就是将int类型的变量自动转换为Integer包装类型的变量。具体来说,

Integer b = 127;	//自动装箱

这句代码的实现原理为

Integer a = Integer.valueOf(127);	//手动装箱

Integer.valueOf(int)方法是装箱过程的关键。让我们看看Integer.valueOf(int)的源码:

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

我们可以看出当 IntegerCache.low < i < IntegerCache.high 的时候,会返回 IntegerCache.cache[i + (-IntegerCache.low)] 这个类似数组值的东西。其中,IntegerCache是Integer类的一个静态内部类,我们点击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() {}
    }

由这个源码我们可以看出 cache是一个IntegerCache类中的数组,它的长度为 (high - low) + 1 即256,当我们使用的 valueOf(int i)中的 i 的范围在[-128,127]时,就会从cache数组中拿出提前创建好的对象引用。总结如下:

  • 缓存范围:IntegerCache类会缓存从-128到127(默认情况下)的整数对象。这个范围内的整数在装箱时会使用缓存对象。
  • 缓存机制:当调用Integer.valueOf(int)方法时,如果参数在缓存范围内,就会返回缓存中的对象引用;如果不在缓存范围内,就会创建新的Integer对象。

所以当我们创建[-128, 127] 范围的Integer类型的变量时,无论创建多少次对象,最终的地址都会指向cache缓存数组中已经创建的同一个地址。

3、避免128陷阱的方法

这就是128陷阱的源码解释,那么当我们了解了这个“陷阱”的原理之后应该怎么规避它呢?
其实很简单,一切的根源都在于使用 “==” 判断两个引用类型是否相等,那么我们使用Integer类已经重写的equals()方法来代替 “==” 就可以避开这个“陷阱”了。

  • 9
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值