java 自动拆箱的陷阱

  java  自动拆箱运用非常广泛。但是这里面有一些“陷阱”。废话不多说,来看一段代码:

 

public static void main(String[] args) {
	Integer a=1;
	Integer b=2;
	Integer c=3;
	Integer d=3;
	System.out.println(c==(a+b));
	System.out.println(c==d);
	System.out.println(c.equals(d));
	Integer f=200;
	Integer e=200;
	System.out.println(e==f);
	System.out.println(e.equals(f));
}

打印结果:

true

true

true

false

true

如果说以上的运算都进行自动拆箱那打印的结果应该都是true。在这里先说明一下== 符号并不会发生自动拆箱,所以也就出现了以上的问题。但是仔细观察一下,就有人会说,那不是明明c==d吗?为了解开谜团,我们必须要了解这个装箱过程。我们来看一下对以上代码的反汇编结果:



从以上的代码片段可以发现,原来是调用了Integer.valueOf这个类方法。我们来看一下这个类方法:

  /**
     * Returns a {@code Integer} instance for the specified integer value.
     * <p>
     * If it is not necessary to get a new {@code Integer} instance, it is
     * recommended to use this method instead of the constructor, since it
     * maintains a cache of instances which may result in better performance.
     *
     * @param i
     *            the integer value to store in the instance.
     * @return a {@code Integer} instance containing {@code i}.
     * @since 1.5
     */
    public static Integer valueOf(int i) {
        return  i >= 128 || i < -128 ? new Integer(i) : SMALL_VALUES[i + 128];
    }

    /**
     * A cache of instances used by {@link Integer#valueOf(int)} and auto-boxing
     */
    private static final Integer[] SMALL_VALUES = new Integer[256];

看到以上的代码,我相信清楚了为什么会发生以上的结果了。因为缓存了[-128,127] 。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值