gpt4 book ai didi

java - hashCode() 必须返回素数吗?

转载 作者:行者123 更新时间:2023-12-02 00:51:52 28 4
gpt4 key购买 nike

hashCode()方法的签名是

public int hashCode(){
return x;
}

在这种情况下 x 必须是 int(primitive) 但请有人向我解释一下这个数字hashCode() 返回的值必须是质数、偶数等,还是没有指定?我问这个问题的原因是我在不同的ID中看到它自动生成的代码总是返回一个素数,所以我需要知道为什么?

提前致谢

最佳答案

实际上有一个关于 hashCode() 的非常明确的约定:

Returns a hash code value for the object. This method is supported for the benefit of hashtables such as those provided by java.util.Hashtable. 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 hashtables.

As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the Java™ programming language.)

Documentation for the java.lang.Object class

返回的内容取决于您,如果您愿意,您可以为每个对象实例发出 0 。这可能是一个坏主意,但完全有效。它绝不总是素数。如文档中所述,默认实现仅返回对象的内部地址 - 这与检查引用相等性的 equals 默认实现一致。

通常,您可以通过对构成对象状态的字段调用 hashCode 方法来构造哈希,例如:

class Person {
private String firstName;
private String lastName;

@Override
public int hashCode() {
return firstName.hashCode() + lastName.hashCode();
}
}

不过,请记住,每当您认为对象状态的表示发生变化时,都要更新 hashCodeequals

关于java - hashCode() 必须返回素数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2689090/

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