s-day01--Objects类的equals方法

This commit is contained in:
xx
2026-10-10 13:47:18 +08:00
parent fe0884a99e
commit fbea00ed59
2 changed files with 74 additions and 0 deletions
@@ -0,0 +1,35 @@
package com.inmind.object01;
/*
boolean equals(Object obj) 指示一些其他对象是否等于本对象。
== :
基本数据类型:比较2个数据是否相同
引用数据类型:比较的是地址是否相同
在实际开发中,地址值对我们没有太大的作用,比较关心数据内容,经常将内容相同的2个对象,看作是同一个,要使用Object的equals方法
Object父类的源码:
public boolean equals(Object obj) {
return (this == obj);
}
如果父类的内容比较功能,不符合子类的需求,那就重写equals方法
总结:每个对象的equals方法继承自Object类,默认使用==比较2个对象是否相同,==比较的是地址,这个
不符合程序员业务的需求,我们都会在每个自定义类中重写equals,不用手写,直接alt+insert自动生成
*/
public class Demo03 {
public static void main(String[] args) {
//比较2个引用数据类型的内容是否相同
String s1 = "123";
String s2 = "123";
System.out.println(s1 == s2);//true,字符串比较特殊,是保存在常量池的,所以此处地址相同
Student s3 = new Student("张三", 20);
Student s4 = new Student("张三", 20);
System.out.println(s3 == s4);//false
System.out.println(s3.equals(s4));//希望是true,但是一开始还是false!!!为何?怎么办呢??
}
}
@@ -1,9 +1,19 @@
package com.inmind.object01;
import java.util.Objects;
public class Student extends Person {//直接继承person类,间接继承了Object
private String name;
private int age;
public Student() {
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
@@ -27,4 +37,33 @@ public class Student extends Person {//直接继承person类,间接继承了Ob
", age=" + age +
'}';
}
/*@Override
public boolean equals(Object obj) {
//1.优先判断地址,如果同一个地址,那就不用判断了,一定是同一个对象
if (this == obj) {
return true;
}
//2.如果地址不同,先判断类型,再判断属性
if (!(obj instanceof Student)) {
return false;
}
//3.要比较学生的属性
Student s = (Student) obj;
if (this.age == s.age && this.name.equals(s.getName())) {
return true;
}else{
return false;
}
}*/
@Override
public boolean equals(Object o) {
if (o == null || this.getClass() != o.getClass()) return false;
Student student = (Student) o;
return age == student.age && Objects.equals(name, student.name);
}
}