Integer用==比较时127相等128不相等的原因

11 篇文章 0 订阅
for (int i = 0; i < 150; i++) {
    Integer a = i;
    Integer b = i;
    System.out.println(i + " " + (a == b));
}

部分结果如下:

124 true
125 true
126 true
127 true
128 false
129 false
130 false
131 false

结合上述例子,每一次 i和j都会被装箱为Integer   既然是对象,那就不应该返回true了啊?

那我就用看看 i和j的内存地址

for(int i=0;i<150;i++){
    Integer a=i;
    Integer b=i;
    System.out.println(a + " " + b + " " + System.identityHashCode(a) + "" + System.identityHashCode(b));
}
地址结果如下:

123 123 1531448569 1531448569
124 124 1867083167 1867083167
125 125 1915910607 1915910607
126 126 284720968 284720968
127 127 189568618 189568618
128 128 793589513 1313922862
129 129 495053715 1922154895

 

竟然....... 竟然从0到127不同时候自动装箱得到的是同一个对象!从128开始才是正常情况。  那看看源码

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

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值