java 自动拆箱的陷阱

来源:互联网 发布:阿里经典java面试题 编辑:程序博客网 时间:2024/05/04 04:55

  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] 。

1 0