《core java》给出的 equals() 方法需要满足的原则
- It is reflexive: For any non-null reference x, x.equals(x) should return true. 自反性
- It is symmetric: For any references x and y, x.equals(y) should return true if and
only if y.equals(x) returns true. 对称性 - It is transitive: For any references x, y, and z, if x.equals(y) returns true and
y.equals(z) returns true, then x.equals(z) should return true. 传递性 - It is consistent: If the objects to which x and y refer haven’t changed, then
repeated calls to x.equals(y) return the same value. 一致性/不变性 - For any non-null reference x, x.equals(null) should return false. 空值false
These rules are certainly reasonable. You wouldn’t want a library
标准重写
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
BaseStudent that = (BaseStudent) o;
return Objects.equals(name, that.name);
}
完整测试‘
import java.util.Objects;
public class EqualsTest {
public static void main(String[] args) {
// Student ISA BaseStudent
System.out.println(BaseStudent.class.getClassLoader().getClass() == Student.class.getClassLoader().getClass());
BaseStudent baseStudent = new Student("小明",10);
Student student = new Student("小明",99);
Student otherStudent = new Student("小明",19);
// 自反性
System.out.println(student.equals(student));
// 对称性
System.out.println(student.equals(baseStudent));
System.out.println(baseStudent.equals(student));
// 传递性
// 空返回false
System.out.println(student.equals(null));
}
}
class BaseStudent {
private String name;
private Integer age;
public BaseStudent() {
}
public BaseStudent(String name, Integer age) {
this.name = name;
this.age = age;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
BaseStudent that = (BaseStudent) o;
return Objects.equals(name, that.name);
}
}
class Student extends BaseStudent{
private String name;
private Integer age;
public Student() {
}
public Student(String name, Integer age) {
this.name = name;
this.age = age;
}
}