> For the complete documentation index, see [llms.txt](https://amartyushov.gitbook.io/tech/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://amartyushov.gitbook.io/tech/programming-languages/java/features/hashcode-and-equals.md).

# 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)*****&#x20;must return the same result as&#x20;*****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](https://www.baeldung.com/java-equals-hashcode-contracts#3-violatingequals-symmetry-with-inheritance)

### Contract for HashCode()

**All three criteria in the&#x20;*****hashCode()*****&#x20;contract mention the&#x20;*****equals()*****&#x20;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
