๐ Java Interview Questions โ Episode 6
๐ก What is the contract between equals() and hashCode() in Java?
๐ And where is it used?
In Java, whenever you override equals(), you must also override hashCode() โ this is known as the equals-hashCode contract. Hereโs the rule:
โ
If two objects are equal according to equals(), then they must have the same hashCode().
โ The reverse is not necessarily true: two objects with the same hashCode() arenโt always equal.
๐ Where is it used?
This contract is essential when working with collections like:
๐ฃ HashSet
๐ฃ HashMap
๐ฃ Hashtable
Without following this contract, your objects may behave unexpectedly in hash-based structures โ like being "lost" in a HashSet even though they seem equal. โ ๏ธ
๐ก Always override both methods together for correct behavior in hash-based collections.