Java 有关自动装箱的一个有趣的小东西

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/weixin_45614509/article/details/102748979

这个是 《深入理解Java虚拟机》书中的一个例子,思考下下面的这段代码运行的结果是什么?

    public static void main(String[] args) {
        Integer a = 1;
        Integer b = 1;
        Integer c = 3;
        Integer d = 3;
        Integer e = 138;
        Integer f = 138;
        Long g = 3L;

        System.out.println(c == d);
        System.out.println(e == f);
        System.out.println(c == (a + b));
        System.out.println(c.equals(a + b));
        System.out.println(g == (a + b));
        System.out.println(g.equals(a + b));
    }

了解这个首先要知道 == 和 equals 的区别, == 比较的对象在内存中的地址是否相等,也就是比较的是两个是否是同一个对象。 equals 方法一般比较的是对象的内容是否相同,但是如果没有重写 equals 方法,就是调用 Object 的 equals 方式,实际上还是使用 == 来比较的。

了解这个之后继续向下看:

c == d

c和d 虽然都是3,但是使用==在比较,就相当于比较Interger类型的c和Interger类型的d的内存地址是否相同。所以猜测结果是false。

e==f
同理

c==(a+b)

在执行 a+b 的时候因为a、b都是Integer两个对象肯定无法相加,所以会将 a 和 b 自动拆箱成int,然后相加的结果也是 int ,int类型的3 和 Integer 类型的3肯定是不相等的。所以猜测是false

c.equals(a + b)

因为Integer 比较的是值是否相等,而不是比较内存地址,所以猜测结果是 true

g == (a + b)

同理,猜测false

g.equals(a + b)

因为 g 是Long类型的,所以和 int 类型的 a+b 比较结果肯定是false。所以猜测是false


然后运行结果如下:

true
false
false
false
false
false

猜错了两个,来看一下第一个:

        Integer c = 3;
        Integer d = 3;
        System.out.println(c == d);

Integer c = 3; 因为自动装箱机制,就相当于Integer.valueOf(3)Integer d = 3同理,按理说应该是两个不同的对象,但是内存地址的比较结果竟然是一样的。我们点进去查看一下源码:

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

嗯?IntegerCache 是什么鬼?看名字可以看得出是用来缓存的,这样的话就能理解为什么 c==d 的结果是true了,在点击去看一下源码:

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

IntegerCache 使用了一个 Integer 数组将 -128~127 之间,也就是byte的取值范围内的数据给缓存了起来,每次使用 Integer.valueOf 的时候都会从这里去取,所以实际上 c 和 d 是一个对象。

c.equals(a + b)

这个来看下源码就知道了:

    public boolean equals(Object obj) {
        if (obj instanceof Integer) {
            return value == ((Integer)obj).intValue();
        }
        return false;
    }

在源码中先进行的 instanceof 来判断是否是同一种对象,因为 a+b 的结果是int类型,是属于 Object 的,并没有发生自动装箱,所以obj instanceof Integer条件不成立,直接返回false。


在实际工作中应该避免这样使用自动装箱与拆箱

猜你喜欢

转载自blog.csdn.net/weixin_45614509/article/details/102748979