Integer类==与equals区别与使用

来源:互联网 发布:inpaint mac破解版 编辑:程序博客网 时间:2024/06/06 09:55
public static void test(){      Integer a=1;      Integer b=1;      System.out.println(a==b);      System.out.println(a.equals(b));  }

输出结果: 
true 
true 

 public static void test(){      Integer a=150;      Integer b=150;      System.out.println(a==b);      System.out.println(a.equals(b));  }

输出结果: 
false 
true 
结论:大家都知道”==“是比较两个变量的值是否相等、对于引用型变量表示的是两个变量在堆中存储的地址是否相同。 equals操作表示的两个变量是否是对同一个对象的引用,即堆中的内容是否相同。 
但是为什么等于1的时候==返回是true呢?

Integer a=150;//会将int类型通过valueof转换成Integer类型。下面是valueof源码。static final int low = -128; public static Integer valueOf(int i) {        if (i >= IntegerCache.low && i <= IntegerCache.high)            return IntegerCache.cache[i + (-IntegerCache.low)];        return new Integer(i);    }

也就是说在-128到127之间的值会缓存到IntegerCache.cache中,所以在Integer x=在-128到127之间时,返回的是同一个对象,所以出现了上文的情况。(如果换成 >、>=、<、<=会出现什么情况呢?这中情况会自动拆箱比较值,也就是下面的拆箱操作。) 
在看下面代码

public static void test(){      Integer a=150;      int b=150;      System.out.println(a==b);      System.out.println(a.equals(b));  }

输出结果: 
true 
true 
原理:因为与初始化值做比较的时候,会将封装类型进行拆箱操作,转换为基本类型。这里比较的就是基本类型的值了。

原创粉丝点击