且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

当我覆盖equals()方法时,为什么要覆盖hashCode()?

更新时间:2022-12-14 18:38:50

它适用于您,因为您的代码不使用任何需要 hashCode()$的功能(HashMap,HashTable) c $ c> API

It works for you because your code does not use any functionality (HashMap, HashTable) which needs the hashCode() API.

但是,您不知道您的课程(可能不是一次性写入)将在以后调用确实使用其对象作为哈希键的代码,在这种情况下,事情将受到影响。

However, you don't know whether your class (presumably not written as a one-off) will be later called in a code that does indeed use its objects as hash key, in which case things will be affected.

根据对象类的文档


hashCode的一般合约是:

The general contract of hashCode is:


  • 每当调用它时在执行Java应用程序期间,在同一个对象上不止一次,hashCode方法必须始终返回相同的对象整数,前提是没有修改用于对象的等比较的信息。从应用程序的一次执行到同一应用程序的另一次执行,此整数不需要保持一致。

  • 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.

如果两个对象根据等于(Object)方法,然后在两个对象中的每一个上调用hashCode方法必须产生相同的整数结果