Contents    Page-10    Prev    Next    Page+10    Index   

Java .hashCode()

The Java .hashCode() returns int, which could be positive or negative. To use the .hashCode() as an array index, make it positive (e.g. with Math.abs()) and make it modulo the table size.

The requirements of a .hashCode() include:

  1. When called on the same object, .hashCode() must always return the same value during a given execution of a program (but could be different on different executions).

  2. If two objects are .equals(), .hashCode() must return the same value for both.

The .hashCode() that is inherited from Object may use the memory address of an object as the hash code; this will differ between executions. Therefore, it is preferable to write your own .hashCode() for application data structures.