自动装箱的陷阱

10 篇文章 1 订阅
3 篇文章 0 订阅
今天在阅读 jvm关于自动装箱部分的内容时,对最后一个案例 自动装箱的的陷阱感到疑惑。解决后特此记录
        Integer a=1;
        Integer b=1;
        Integer c=128;
        Integer d=128;
        Integer e=127;
        System.out.println(a==b);
        System.out.println(c==d);
        System.out.println(c==(a+e));

对于 这段代码,输出结果

true
false
true

what?难道 1和1相同,128和128就不相同了吗?,听我娓娓道来

上述代码的编译结果,类中方法体在编译后代码存储在code属性中,对这些内容不感兴趣可以直接跳过
Code:
  stack=4, locals=6, args_size=1
     0: iconst_1                 /*将字面量 1 压入栈顶*/
     1: invokestatic  #2                  // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
     /*调用 Integer.valueOf () l,并且通过操作数栈来传参。返回引用压入操作数栈*/
     4: astore_1                  /*将栈顶元素存储到 变量槽1 */
     5: iconst_1
     6: invokestatic  #2                  // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
     9: astore_2                                 
    10: sipush        128
    13: invokestatic  #2                  // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
    16: astore_3
    17: sipush        128
    20: invokestatic  #2                  // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
    23: astore        4
    25: bipush        127
    27: invokestatic  #2                  // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
    30: astore        5
    32: getstatic     #3                  // Field java/lang/System.out:Ljava/io/PrintStream;
    35: aload_1
    36: aload_2
    37: if_acmpne     44           /*比较栈顶的俩个元素,相同则执行下一条指令,否则则调转到 44*/
    40: iconst_1
    41: goto          45
    44: iconst_0
    45: invokevirtual #4                  // Method java/io/PrintStream.println:(Z)V
    48: getstatic     #3                  // Field java/lang/System.out:Ljava/io/PrintStream;
    51: aload_3
    52: aload         4
    54: if_acmpne     61
    57: iconst_1
    58: goto          62
    61: iconst_0
    62: invokevirtual #4                  // Method java/io/PrintStream.println:(Z)V
    65: getstatic     #3                  // Field java/lang/System.out:Ljava/io/PrintStream;
    68: aload         4
    70: invokevirtual #5                  // Method java/lang/Integer.intValue:()I
    73: aload_1
    74: invokevirtual #5                  // Method java/lang/Integer.intValue:()I
    77: aload         5
    79: invokevirtual #5                  // Method java/lang/Integer.intValue:()I   ,自动拆箱比较的是 内部封装的基本类型
    82: iadd
    83: if_icmpne     90
    86: iconst_1
    87: goto          91
    90: iconst_0
    91: invokevirtual #4                  // Method java/io/PrintStream.println:(Z)V
    94: return

从上面的编译结果来看在执行代码的时候,编译器为我们自动装箱,调用 Integer.valueOf()。而且从上述字节码可以看出,在包装类进行比较的时候(==),当不遇到算数运算的时候,不会自动拆箱,而是比较其指向的对象引用。

那么如果没有自动拆箱,a==b 比较引用应该是false呀,实则不然。

看一下自动装箱的源代码,就可一目了然

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

这段代码的关键之处就在于 if 语句,返回的是一个cache数组的中的元素

    //cache数组被封装到 Integer的私有内存类中, 
    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;               //调试结果  JDK8   中  hiehg==127

            cache = new Integer[(high - low) + 1];        //创建一个大小为   256  的数组
            int j = low;
            for(int k = 0; k < cache.length; k++)
                cache[k] = new Integer(j++);                //初始化   index 0  ~ 255  value  -128~127

            // range [-128, 127] must be interned (JLS7 5.1.7)
            assert IntegerCache.high >= 127;
        }

        private IntegerCache() {}
    }
所以 结合上面的代码,我们知道 当 自动装箱的值在 -128~127的时候,返回的是cache中的引用

所以 a 与 b返回的相同的引用,值相同,而c,d则指向俩个不同的对象。虽然这样会带来的一些小的陷阱,但是我认为这样在大量的自动装箱操作发生时,可以提高效率,不用频繁创建Integer对象。一把双刃剑呀。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值