Integer类型的整数比较大小

本文深入探讨了Java中Integer类型数值比较的常见误区,详细解释了-128至127范围内Integer对象的缓存机制,以及超出此范围时使用'=='与equals()方法的区别。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

之前没注意过Integer类型比较数值大小,一直在用 == 
某天,写的一段程序没跑通,才注意到这个问题

举个例子

  public static void main(String[] args) {   
     Integer  a = 1 ;     
     Integer  b = 1 ; 
     System.out.println(a == b);   
     System.out.println(a.equals(b));     
     a = 1515; 
     b = 1515;  
     System.out.println(a == b);  
     System.out.println(a.equals(b));   
  }  
 结果:    true    true    false    true 

 

原因

  • Integer.valueOf() 
    上述Integer类型在比较大小的时候调用了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) {        assert IntegerCache.high >= 127;        if (i >= IntegerCache.low && i <= IntegerCache.high)            return IntegerCache.cache[i + (-IntegerCache.low)];        return new Integer(i);    }

-128到127之间的数,比较数值大小的时候用equals.() 和 == 得到的结果是一样的,超出了这个范围,用 == 比较大小就相当于判断是否是同一个对象了。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值