Discuss / Java / 廖老师您的equals方法实现会有点bug吗?

廖老师您的equals方法实现会有点bug吗?

Topic source
public boolean equals(Object o) {
    if (o instanceof Person) {
        Person p = (Person) o;
        return this.name.equals(p.name) && this.age == p.age;
    }
    return false;
}

考虑一种情况,如果Student是Person的子类,并且name和age相等的话,则也认为是equal。

例如:

Person p = new Person("Bob", 12);
Student s = new Student("Bob", 12);
p.equals(s); //使用您的equals实现应该返回true

您看这样的equals实现会不会修复这个bug:

public boolean equals(Object other) {  if (this == other) return true;  if (other == null || getClass() != other.getClass()) return false;  Person person = (Person)other;  return age == person.age &&          Objects.equals(name, person.name);}

廖雪峰

#2 Created at ... [Delete] [Delete and Lock User]

equals是你认为相同就是相同,允许子类和自己比就用instanceof,不允许子类和自己比就用class比

没有标准答案


  • 1

Reply