zoukankan      html  css  js  c++  java
  • ==与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
  • 相关阅读:
    SQL基础复习03--数据查询SQL语句(单表查询)
    SQL基础复习02--数据操纵SQL语句
    数据结构与算法01--复杂度
    SQL基础复习01--SQL基础与数据定义SQL语句
    Azure Data Studio的初步了解与使用
    ASP.NET Core Web API 使用DynamicLinq实现排序功能
    Vue3-说说Vue 3.0中Treeshaking特性?举例说明一下?
    JavaScript高频手写面试题
    Java常用文件操作-1
    Java 架构师之路(2)
  • 原文地址:https://www.cnblogs.com/yanze/p/10033845.html
Copyright © 2011-2022 走看看