#1 most askedVery commonMediumCore Java & OOP
The equals() and hashCode() contract
New to Core Java & OOP? Learn it from scratch firstInheritance vs Composition โ
๐ข Asked in real interviews
No reports yet. Were you asked this? Be the first to say where.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.
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 โ