The equals/hashCode Contract
Why both must agree.
Two Methods, One Contract
Every Java object inherits equals() and hashCode() from Object.
When you override one, you almost always must override the other. They form a binding contract that hash-based collections rely on.
public class Main {
public static void main(String[] args) {
Object a = new Object();
Object b = new Object();
System.out.println(a.equals(b));
System.out.println(a.hashCode() == b.hashCode());
}
}The Core Rule
The contract states:
- If
a.equals(b)is true, thena.hashCode()must equalb.hashCode(). - If hash codes differ, the objects are guaranteed unequal.
Equal objects must have equal hash codes. The reverse is not required.
public class Main {
public static void main(String[] args) {
String s1 = "hello";
String s2 = "hel" + "lo";
System.out.println(s1.equals(s2));
System.out.println(s1.hashCode() == s2.hashCode());
}
}All lessons in this course
- How HashMap Works
- The equals/hashCode Contract
- Implementing hashCode
- Treeification and Performance