What is the contract between equals and hashCode, and why must two 'equal' objects produce the same hash code?
Last updated
Contract: objects equal under
equals()must return the samehashCode(). Unequal objects may collide but ideally shouldn't.Why: a
HashMappicks a bucket by hash first, then checksequals(). Equal objects with different hashes land in different buckets and lookups fail.Always override both using the same fields, and never hash on fields you mutate while the object is in a hash-based collection.