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

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

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));
    }
}

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

true
true
true
true

结果实际执行效果是

true
true
false
true

仔细研究了一下,发现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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值