进阶day01-Object类的equals方法的重写实现

This commit is contained in:
2026-01-26 14:02:58 +08:00
parent 8abe3f5b03
commit 547a7ce1d0
3 changed files with 59 additions and 0 deletions

View File

@@ -10,6 +10,16 @@ boolean equals(Object obj) 判断2个对象的内容是否相同
equals比较的是内容
注意每个引用数据类型都默认直接或者间接继承Object也就是说每个引用类型都有它的equals方法
Object类底层equals源码
public boolean equals(Object obj) {
return (this == obj);
}
如果父类的内容比较功能不符合子类需求那就重写equals方法即可
总结每个对象的equals方法继承自Object类默认使用==比较地址值,这个对于我们而言,不满足咱们需求
因此我们会在每个类中重写equals方法不用手动写直接alt+insert自动生成
*/
public class Demo02 {
public static void main(String[] args) {
@@ -18,6 +28,13 @@ public class Demo02 {
System.out.println(str1 == str2);//false,比较的是地址
System.out.println(str1.equals(str2));//true,比较的是内容
System.out.println("-------------------------------");
//一般在开发中,自定义类的对象也会进行比较
Person p1 = new Person("张三", 18);
Person p2 = new Person("张三", 18);
System.out.println(p1 == p2);//false
//false,希望是true但是底层源码是==比较地址false
System.out.println(p1.equals(p2));//true
}
}