gpt4 book ai didi

java - 用父类(super class) hashCode 和对象覆盖 hashCode

转载 作者:行者123 更新时间:2023-11-29 08:23:33 25 4
gpt4 key购买 nike

我是否需要使用super.hashcode()来计算this.hashcode()

IDE(例如 IntelliJ Idea)可以生成 equals 和 hashcode。它可以使用 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;
}
}

现在让我们有两个同名的实例。他们的 hascode 会有所不同。

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]

最佳答案

在您的示例中,您不应使用 super.hashCode(),因为它将调用 Object 标识 hashCode()。这会破坏 contract between hashCode() and equals() , 根据Object.hashCode() javadoc is

The general contract of hashCode is:

  • Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.
  • If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.
  • It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hash tables.

您必须确保当两个对象 equal() 时,它们的 hashCode() 相同。 IntelliJ 通过在两种方法中使用相同的字段来确保这一点。

关于java - 用父类(super class) hashCode 和对象覆盖 hashCode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55421151/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com