Skip to content

Hash Code Input Data

Question

Calculating hashcode should be based on what type of data?

Short interview answer

Base a hash code on the same value-defining data used by equality. If two objects are equal according to Equals, they must produce the same hash code, and the fields used must not change while the object is used as a key in a hash-based collection.

Detailed answer

For an immutable Money value where equality compares currency and amount, both fields belong in the hash calculation. An internal cache timestamp does not, because it is not part of the value’s identity. Conversely, including a mutable property that equality ignores makes lookup behavior difficult to reason about. Hash codes need not be unique; their job is to distribute values so a hash table can narrow its equality comparisons. The essential contract is equal objects have equal hash codes.

Sources