Integer equals和==在自动拆装箱里的坑

来源:互联网 发布:淘宝一淘怎么报名 编辑:程序博客网 时间:2024/06/05 15:19

前两天看到一个面试题,大体就是下面这样的代码:

public class Test {    public static void main(String[] args) throws Exception {        Integer i1 = 10, i2 = 10, i3 = 128, i4 = 128;        System.out.println(i1 == i2);        System.out.println(i1.equals(i2));        System.out.println(i3 == i4);        System.out.println(i3.equals(i4));    }}

看这一段代码,我第一反应就是

truetruetruetrue

结果实际执行效果是

truetruefalsetrue

仔细研究了一下,发现JVM在自动拆装箱的时候会调用valueOf()方法,让我们来看一下Integer的valueOf()方法:

/** * Returns an {@code Integer} instance representing the specified * {@code int} value.  If a new {@code Integer} instance is not * required, this method should generally be used in preference to * the constructor {@link #Integer(int)}, as this method is likely * to yield significantly better space and time performance by * caching frequently requested values. * * This method will always cache values in the range -128 to 127, * inclusive, and may cache other values outside of this range. * * @param  i an {@code int} value. * @return an {@code Integer} instance representing {@code i}. * @since  1.5 */ public static Integer valueOf(int i) {    if (i >= IntegerCache.low && i <= IntegerCache.high)        return IntegerCache.cache[i + (-IntegerCache.low)];    return new Integer(i);}

注释里写明了Integer会缓存[-128, 127]之间的值,结合代码也可以看出如果Integer对象携带的整形如果是[128, 127]之间则直接返回这个Integer,否则新建一个Integer。

这个坑就显而易见了, Java中==比较的是地址,两个不同的对象地址显然不一样,所以会有上面令我匪夷所思的结果。
这坑让我意识到即使Java里有自动拆装箱, 也不能依赖这个特性,否则就是深渊呐,对象还是老老实实的用equals(T)比较吧。

理解可能有误,望大家指出理解错误之处,多谢。

0 0
原创粉丝点击