此博客是本人从学生时代开始做笔记所用, 部分是工作所遇问题,做填坑笔记,部分闲来查阅资料,加上自己的理解所总结的学习笔记, 常忙得不可开交,若漏了资料来源,望通知~ 前路漫漫,写点东西告诉自己正在一点点进步,而不要迷失于繁忙。

==与equals的各种情况

== 能用于基本类型之间、基本类型与引用类型之间及相同引用类型之间,不能用于不同引用类型之间

对于基本类型,取值来对比,对于引用类型,取地址来对比

int a= 1;
Integer b= 1;
System.out.println(a== b);//true

Integer 自动拆箱

int a= 1;
Integer b= 1;
System.out.println(a== b);//true

基本类型之间 值得对比

int a= 1;
Double b= 1.0;
//Short b= 1;
//Long b= 1;
System.out.println(a== b);//true

自动拆箱的时机并不局限于基本类型与其对应的包装类型

Integer a= 1;
Integer b= 1;
System.out.println(a== b); //true

Integer a1= 1;
Integer b1= new Integer(1);
System.out.println(a1== b1); //false

类似Integer a= 1直接赋值会被编译为Integer a= Integer.valueOf(1); 源码如下

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之间的数,第一次赋值时会进行缓存,Integer a= 1时,会将1进行缓存,下次再写Integer b= 1时,就直接从缓存中取,就不会new了,使用为true

而如果是通过new Integer()的方式,不会利用缓存。

 

 ----------------------------------------------------------------------------------------------------------------

 

equals

首先,以Short为例,看一下其equals的源码

public boolean equals(Object obj) {
      if (obj instanceof Short) {
          return value == ((Short)obj).shortValue();
      }
      return false;
}

可知,equals()返回值为true的条件是:instanceof为true且值相等,因此:

Short a= 1;
Integer b= new Integer(1);
System.out.println(a.equals(b)); //false instanceof不为true

Integer a1= 1;
Integer b1= new Integer(1);
System.out.println(a1.equals(b1)); //true

 

posted @ 2018-11-28 18:29  炎泽  阅读(159)  评论(0编辑  收藏  举报