128陷阱——源码分析

128陷阱——源码分析

`public static void main(String[] args) {
		Integer aInteger = 101;
		//自动装箱Integer.valueOf(101)
		Integer bInteger = 101;
		System.out.println(aInteger==bInteger);
		Integer cInteger = 1001;
		Integer dInteger = 1001;
		System.out.println(cInteger==dInteger);
		int a = 101;
		//自动拆箱aInteger.intValue()
		System.out.println(a==aInteger);
		int b = 1001;
		System.out.println(b==cInteger);
		//Integer.valueOf(b)
		System.out.println(dInteger==b);
	}`

上面代码的运行结果是:
在这里插入图片描述

为什么前两个答案会出现不同呢?这就是Java的128陷阱。

128陷阱:自动装箱规范要求boolean\byte\char<=127,介于-128~127之间的short和int被包装到固定的对象中。

为什么范围在-128~127之间呢?我们看一下源码。

​ 自动装箱调用函数Integer.valueOf(101);

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






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

可以看到在i>=-128&&i<=127时,直接从缓存数组中取出数据返回,不需要新建对象。不在这个这个范围内,则新建Integer对象,因此地址指向不同,才出现了true和false的情况。在下面的三个true里,则是因为执行了自动拆箱操作。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值