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);}
equals是你认为相同就是相同,允许子类和自己比就用instanceof,不允许子类和自己比就用class比
没有标准答案
Sign in to make a reply
用户6564114687
考虑一种情况,如果Student是Person的子类,并且name和age相等的话,则也认为是equal。
例如:
您看这样的equals实现会不会修复这个bug: