1、== 和 equals 的区别?

使用 == 比较

  • 8种基本数据类型(byte,short,char,int,long,float,double,boolean)比较他们之间的值是否相等。
  • 引用数据类型,比较的是他们在堆内存地址是否相等。每新new一个引用类型的对象,会重新分配堆内存空间,使用==比较返回false。
package com.niuke.first;

public class Demo01 {
    
    
    public static void main(String[] args) {
    
    
        String s1 = "HelloWorld";
        String s2 = new String("HelloWorld");
        if (s1 == s2) {
    
    
            System.out.println("s1 == s2");
        } else {
    
    
            System.out.println("s1 != s2");
        }
        System.out.println(s1.hashCode());//439329280
        System.out.println(s2.hashCode());//439329280
        System.out.println(System.identityHashCode(s1));//608188624
        System.out.println(System.identityHashCode(s2));//1451270520
    }
}


  • 这里可以看到两者的地址值是不同的
  • identityHashCode(),无论重写与否,都可以看到地址值
  • 因此输出 s1 != s2

使用 equals 比较

  • equals方法是Object类的一个方法,Java当中所有的类都是继承于Object这个超类。
  • JDK1.8 Object类equals方法源码如下,即返回结果取决于两个对象的使用==判断结果。
 public static void main(String[] args) {
    
    
        String s1 = "HelloWorld";
        String s2 = new String("HelloWorld");
        if (s1.equals(s2)) {
    
    
            System.out.println("s1 equals s2");
        } else {
    
    
            System.out.println("s1 not equals s2");
        }

        System.out.println(s1.hashCode());//439329280
        System.out.println(s2.hashCode());//439329280
        System.out.println(System.identityHashCode(s1));//608188624
        System.out.println(System.identityHashCode(s2));//1451270520
    }
  • 这里可以看到两者的地址值不同,采用了比较这个时候比较的就是内容
  • 因此两者返回的值是相等

猜你喜欢

转载自blog.csdn.net/AzirBoDa/article/details/127071589