我需要使用super.hashcode()计算this.hashcode()吗?
IDE (例如IntelliJ Idea )可以生成等于和哈希码。它可以使用java.util.Objects。它还可以覆盖super.hashcode()。
//Immutable class to put it into a hash set.
class Person {
private final String name;
// Constructor of not null, getter
@Override
public boolean equals(final Object o) {
if (this == o) return true;
if (!(o instanceof Person)) return false;
final Person that = (Person) o;
return Objects.equals(name, that.name);
}
// Auto generated by idea.
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), name);
}
@Override
public String toString() {
return name;
}
}现在让我们有两个同名的实例。他们的密码会不一样。
public static void main(String[] args) {
Person person1 = new Person("John");
Person person2 = new Person("John");
System.out.println("People are equal: " + person1.equals(person2));
System.out.println("Person 1: " + person1 + ", Hash code: " + person1.hashCode());
System.out.println("Person 2: " + person2 + ", Hash code: " + person2.hashCode());
Set<Person> people = new HashSet<>();
people.add(person1);
people.add(person2);
System.out.println("People: " + people);
}它会打印不同的哈希码。
People are equal: true
Person 1: John, Hash code: -1231047653
Person 2: John, Hash code: -1127452445
People: [John, John]发布于 2019-03-29 15:56:42
在您的示例中,您不应该使用super.hashCode(),因为它将调用Object标识hashCode()。这将破坏equals(),根据 javadoc is
hashCode的总合同是:
您必须确保当两个对象是equal()时,它们的hashCode()是相同的。IntelliJ通过在两个方法中使用相同的字段来确保这一点。
https://stackoverflow.com/questions/55421151
复制相似问题