โ† Java
#1 most askedVery commonMediumCore Java & OOP

The equals() and hashCode() contract

New to Core Java & OOP? Learn it from scratch first
Inheritance vs Composition โ†’
๐Ÿข Asked in real interviews
No reports yet. Were you asked this? Be the first to say where.
I was asked this

Why must you override hashCode() whenever you override equals()? What breaks if you don't?

๐Ÿ”ฎ Predict the output

class Point {
    final int x, y;
    Point(int x, int y) { this.x = x; this.y = y; }
    @Override public boolean equals(Object o) {
        return o instanceof Point p && p.x == x && p.y == y;
    }
    // hashCode() is NOT overridden
}
public class Main {
    public static void main(String[] args) {
        Set<Point> seen = new HashSet<>();
        seen.add(new Point(1, 2));
        System.out.println(new Point(1, 2).equals(new Point(1, 2)));
        System.out.println(seen.contains(new Point(1, 2)));
    }
}

๐ŸŽค Answer it out loud, then check yourself

Say your answer as if the interviewer is listening (30โ€“90 seconds). Then reveal what a strong answer covers and tick what you said.

    โ˜• Java example ยท compiled and run to verify it works
    record Point(int x, int y) {}  // records generate equals, hashCode and toString
    Set<Point> seen = new HashSet<>();
    seen.add(new Point(1, 2));
    System.out.println(seen.contains(new Point(1, 2)));
    
    Answer out loud first, then compare.
    Want to rehearse it?
    Answer this to the AI interviewer and get a verdict โ†’