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
  • 相关阅读:
    主席树模板之区间问题
    简易版第k大(权值线段树+动态开点模板)
    Irrigation
    Petya and Array
    H. Pavel's Party(权值线段树)
    权值线段树入门
    位数差(二分)
    ZYB's Premutation(树状数组+二分)
    单调队列入门
    javaBean为什么要implements Serializable?
  • 原文地址:https://www.cnblogs.com/yanze/p/10033845.html
Copyright © 2011-2022 走看看