Skip to main content

Explain hashCode() and equals() contract.

Junior Java
Quick Answer The contract: objects that are equal (equals() returns true) must have the same hashCode. Objects with the same hashCode may or may not be equal (hash collision). If you break this contract, HashMap and HashSet won't work correctly - equal objects would be stored in different buckets and never found. Always override both together. Use Objects.hash() for a clean implementation.

Answer

If two objects are equal via equals(), their hashCode() must match.
Required for HashMap, HashSet, and other collections.
S
SugharaIQ Editorial Team Verified Answer

This answer has been peer-reviewed by industry experts holding senior engineering roles to ensure technical accuracy and relevance for modern interview standards.

Want to bookmark, take notes, or join discussions?

Sign in to access all features and personalize your learning experience.

Sign In Create Account

Source: SugharaIQ

Ready to level up? Start Practice