Java 自定义 equals 方法:仅根据姓名判断对象相等
下面是一个示例 Java 代码,定义了一个 Student 类,并重写了 equals 方法:
public class Student {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof Student)) {
return false;
}
Student other = (Student) obj;
return this.name.equals(other.name);
}
}
在这个示例中,我们重写了 equals 方法,只要两个 Student 对象的'name'属性相同,就认为它们是相等的。如果两个对象的'name'不同,即使其他属性相同,也会被认为是不相等的。
要注意的是,重写 equals 方法时,还应该重写 hashCode 方法,以保证相等的对象具有相同的哈希码。
原文地址: https://www.cveoy.top/t/topic/oHOR 著作权归作者所有。请勿转载和采集!