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
  • 相关阅读:
    Python高级网络编程系列之第二篇
    Python高级网络编程系列之第一篇
    Python高级网络编程系列之基础篇
    利用Python实现12306爬虫--查票
    Linux Shell脚本欣赏
    Linux Shell脚本 之 条件判断
    VMware Workstation虚拟网络VMnet0、VMnet1、VMnet8的图解
    Linux的虚拟机采用NAT方式时如何能在虚拟机中访问互联网
    Linux的虚拟机拷贝到另外的操作系统时,NAT方式的静态IP无效,一直是获取的DHCP动态地址
    Hadoop
  • 原文地址:https://www.cnblogs.com/yanze/p/10033845.html
Copyright © 2011-2022 走看看