0Pricing
Java Academy · Lesson

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, then a.hashCode() must equal b.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

  1. How HashMap Works
  2. The equals/hashCode Contract
  3. Implementing hashCode
  4. Treeification and Performance
← Back to Java Academy