← Back to libraryQuestion 27 of 273
JavaIntermediate

equals() and hashCode() Contract

📖 Detailed Explanation:

If two objects are equal according to equals(), they MUST have the same hashCode(). This is a contract enforced by the Java language. If you override equals(), you MUST override hashCode() to maintain this consistency. Violating this contract breaks HashMap, HashSet, and other hash-based collections.

🌍 Real-World Example:

If two people are the same (equals), they should have the same ID number (hashCode). Having different IDs for the same person is inconsistent.

🎯 Scenario-Based Interview Question:

What happens if you override equals() but NOT hashCode() and use the object as a key in a HashMap?