HashCode() and Equals()

Default impl of Object.hashCode() always returns different values.

Default impl of Object.equals() implies object identity (is it the same object in memory?)

Contract for Equals()

  • reflexive: an object must equal itself

  • symmetric: x.equals(y) must return the same result as y.equals(x)

  • transitive: if x.equals(y) and y.equals(z), then also x.equals(z)

  • consistent: the value of equals() should change only if a property that is contained in equals() changes (no randomness allowed)

Violation of equals() method can be achieved by inheritance, this is one of the reasons to favour composition over inheritance. LINK

Contract for HashCode()

All three criteria in the hashCode() contract mention the equals() method in some way:

  • internal consistency: the value of hashCode() may only change if a property that is in equals() changes

  • equals consistency: objects that are equal to each other must return the same hashCode

  • collisions: unequal objects may have the same hashCode

  • Always override hashCode() if we override equals()

  • Override equals() and hashCode() for value objects

Last updated