Integer == 和equals的区别

来源:互联网 发布:淘宝卖家如何提前收款 编辑:程序博客网 时间:2024/06/05 15:32

大家对Java的基本类型与封装类都已经很熟悉了。但是在使用中是否了解其中一些基本原理呢。下面代码对不了解基本实现的人可能会颠覆对java的认知。代码如下。

public static void test(){      Integer a=1;      Integer b=1;      System.out.println(a==b);      System.out.println(a.equals(b));  }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

输出结果可能大家都想到了是什么,没错就是: 
true 
true 
在看一下下面代码,会输出什么呢?

 public static void test(){      Integer a=150;      Integer b=150;      System.out.println(a==b);      System.out.println(a.equals(b));  }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

输出结果: 
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);    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

也就是说在-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));  }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

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

public int intValue() {        return value;    }
  • 1
  • 2
  • 3
  • 1
  • 2
  • 3

以上理解为个人看胖哥的书做的一些总结与理解,也是对自我的提高,如有理解错误或偏差的地方望大家留下宝贵意见。

原创粉丝点击