s-day01-Object类的equals方法

This commit is contained in:
2026-07-28 15:22:04 +08:00
parent 38dbdfd5ef
commit daebfc1126
2 changed files with 52 additions and 0 deletions
@@ -0,0 +1,32 @@
package com.inmind.object01;
/*
Object类的equals方法:
boolean equals(Object obj) 指示一些其他对象是否等于本对象(判断对象内容)
==
基本数据类型:比较2个数据值是否相同
引用数据类型:比较的是地址是否相同
在实际开发中,地址值对我们没有太大的作用,比较关心数据内容,经常将内容相同的2个对象,看作是同一个,要使用Object的equals方法
Object父类的源码:
public boolean equals(Object obj) {
return (this == obj);
}
如果父类的内容比较功能,不符合子类(Student)的需求,那就重写equals方法
*/
public class Demo03 {
public static void main(String[] args) {
String s1 = "123";
String s2 = "123";
System.out.println(s1 == s2);// true
//创建2个学生对象(内容相同的2个对象,看作是同一个)
Student stu1 = new Student("张三", 18);
Student stu2 = new Student("张三", 18);
System.out.println(stu1 == stu2);//false
System.out.println(stu1.equals(stu2));//true!
}
}
@@ -19,4 +19,24 @@ public class Student extends Object{
", age=" + age + ", age=" + age +
'}'; '}';
} }
//重写equals方法,不要比较地址,比较内容
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;//地址相同,内容相同
}
//地址不同,判断类型
if (obj instanceof Student) {
//就比较学生的内容
Student s = (Student) obj;
if (this.name.equals(s.name) && this.age == s.age) {
return true;
} else {
return false;
}
} else {
return false;
}
}
} }