【算法基础】equals() 与 “==” 的使用场景

2023-05-16

一、 “==”

1、“==” 的用途

⭕ 用于 基本数据类型(byte,short,char,int,long,float。double,boolean)比较值时: 只要两个变量的 相等,即为 true。

⭕ 用于 引用数据类型 (数组,类,接口,包装类)比较引用(是否指向同一个对象)时,比较两个对象的 地址值 是否相同,即两个引用是否指向同一个对象实体,只有指向同一个对象时,“==” 才返回true。

⭕ 用“==”进行比较时,符号两边的数据类型必须兼容(可自动转换的基本数据类型除外),否则编译出错。

2、代码演示

①、基本数据类型

int i = 10;
int j = 10;
double d = 10.0;
System.out.println(i == j);//true
System.out.println(i == d);//true

②、引用数据类型

String str1 = new String("hello world");
String str2 = new String("hello world");
System.out.println(str1 == str2);//false

二、equals()

1、 equals()的用途

⭕ 是一个 方法,而非运算符。

⭕ 只能适用于 引用数据类型

⭕ Object类中 equals() 的定义:

public boolean equals(Object obj) { return (this == obj); }
// 说明:Object类中定义的equals()和==的作用是相同的:
// 比较两个对象的地址值是否相同.即两个引用是否指向同一个对象实体。

⭕ 但像 StringDateFile包装类 等都重写了Object类中的equals()方法。重写以后,比较的不是两个引用的地址是否相同,而是比较两个对象的 "实体内容"(值) 是否相同。

⭕ 通常情况下,我们自定义的类如果使用equals()的话,也通常是比较两个对象的"实体内容"是否相同。那么,我们就需要对Object类中的equals()进行重写,重写的原则:比较两个对象的实体内容是否相同

2、 代码演示

①、引用类型equals()方法

//Person为自定义的类,没有对equals()进行重写
Person p1=new Person();
Person p2=new Person();
System.out.println(p1.equals(p2));//false

// String 和 Date 底层都对equals()进行了重写
String str1 = new String("小老师ir");
String str2 = new String("小老师ir");
System.out.println(str1.equals(str2));//true

Date date1 = new Date(32432525324L);
Date date2 = new Date(32432525324L);
System.out.println(date1.equals(date2));//true

②、实体类重写equals()方法

public class Customer {

    private String name;
    private int age;
    
    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (obj == null) return false;
        if (getClass() != obj.getClass()) return false;
            
        Customer other = (Customer) obj;
        if (age != other.age) return false;

        if (name == null) {
            if (other.name != null) return false;
        } else if (!name.equals(other.name)) return false;
        
        return true;
    } 
}

三、equals() 与 “==” 的区别

1、概述

“==” 既可以比较基本类型也可以比较引用类型。对于基本类型就是比较值,对于引用类型就是比较内存地址。

equals 的话,它是属于 java.lang.Object 类里面的方法,如果该方法没有被重写过默认也是 “==”` ;我们可以看到 String 等类的 equals()方法是被重写过的,而且 String 类在日常开发中用的比较多,久而久之,形成了equals 是比较值的错误观点。

⭕ 具体要看自定义类里有没有重写 Object 的 equals() 方法来判断。

⭕ 通常情况下,重写 equals() 方法,会比较类中的相应属性是否都相等。

2、代码演示

int it = 65;
float fl = 65.0f;
System.out.println(6565.0f是否相等?” + (it == fl)); //true

char ch1 = 'A';
char ch2 = 12;
System.out.println("65和'A'是否相等?" + (it == ch1));//true
System.out.println("12和ch2是否相等?" + (12 == ch2));//true

String str1 = new String("hello");
String str2 = new String("hello");
System.out.println("str1和str2是否相等?"+ (str1 == str2));//false
System.out.println("str1是否equals str2?"+(str1.equals(str2)));//true

System.out.println(“hello” == new java.util.Date()); //编译不通过
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

【算法基础】equals() 与 “==” 的使用场景 的相关文章

随机推荐