有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java更多关于equals和hashCode的信息

我理解equalshashCode方法之间的合同。如果equals被重写,那么hashCode也应该被重写。我是否可以重写hashCode方法以始终返回相同的值,比如int 23?我是否可以重写hashCode方法,在每次调用时返回一个随机数


共 (1) 个答案

  1. # 1 楼答案

    您不应该重写hashCode以返回随机值。对于同一实例,它应该始终返回相同的值

    这一点在Javadoc中明确说明:

    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.

    您不应该返回常量值,因为在HashMapHashSet等类中使用时,它会产生非常糟糕的hashCode

    Javadoc中也提到了这一点:

    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.