Java Integer 比较

Java中的Integer比较

1.一次开发过程中比较Integer竟然用了==。。。。

  Integer对象的比较,先看下代码:

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

package test;

 

 

public class IntegerEqual {

    public static void main(String[] args) {

        // TODO Auto-generated method stub

  

        Integer a = 1;

        Integer b = 1;

        Integer c = 2000;

        Integer d = 2000;

         

         

        System.out.println(a==b);

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

     

    }

 

}

  相信很多人一看到这段代码,就会感觉输出的结果是true,true;实际上这段代码的输出结果是true,false;这是为什么呢?同样的对象为什么比较的结果不一样呢?

2.结果分析

  先来分析下Integer a=1;的实现方式,1是数字是怎么放到Integer这个对象中去的;我们知道这是JDK5新增的语法自动装箱和拆箱功能实现的,可是具体的这个装箱功能室如何实现的呢?我们先来看下Integer.valueOf()这个方法,因为这是Integer默认的装箱的实现方式:

 

 

 

 

 

 

 

 

 

 

 

/**

    * Returns a <tt>Integer</tt> instance representing the specified

    * <tt>int</tt> value.

    * If a new <tt>Integer</tt> 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.

    *

    * @param  i an <code>int</code> value.

    * @return a <tt>Integer</tt> instance representing <tt>i</tt>.

    * @since  1.5

    */

   public static Integer valueOf(int i) {

       if(i >= -128 && i <= IntegerCache.high)

           return IntegerCache.cache[i + 128];

       else

           return new Integer(i);

   }

  这是JDK5的时候新增的方法,先来简单分析下这个方法具体做了什么事情;原来它内部维护了一个缓存池,它总是Integer缓存池中获取Integer对象,超出了其缓存池(-128到127),它才new新的Integer对象。只要在这个范围内,都是直接取出对象而不是创建,所以值总是相等的,但是如果超过了这个范围,那么它就会创建新的对象(-2147483648到-128和127到2147483647)(Integer.MAX_VALUE:2147483647,Integer.MIN_VALUE:-2147483648),一旦是创建的对象,那么比较的是对象自然是不相等,即使值是相等的。

3.总结

 

 

 

 

 

 

public boolean equals(Object obj) {

 if (obj instanceof Integer) {

     return value == ((Integer)obj).intValue();

 }

 return false;

 }

  因为这个方法取得是具体的值,所以不管是多少,具体的结果总是相等的。所以比较Integer的时候不能用== 可以用equals 或者Integer.intValue ==

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值