Interview Question

equals() and hashCode() contract?

Equal objects must produce equal hash codes.

💡 Concept ✅ Quick Revision ☕ Java

Answer

equals defines logical equality and hashCode supplies a hash value consistent with that equality. • equals must be reflexive, symmetric, transitive, consistent, and false for null. • Equal objects must have equal hash codes. • Unequal objects may still have the same hash code.

Example

Code
record User(int id) {}
User a = new User(1);
User b = new User(1);
System.out.println(a.equals(b));
System.out.println(a.hashCode() == b.hashCode());
Output
true
true

Quick Revision

Equal objects must produce equal hash codes.