Skip to main content
equals, hashCode, compareTo · Topic 2 of 6

The equals contract

Definition​

equals says when two objects count as the same value. A correct equals is reflexive (x equals x), symmetric (if x equals y then y equals x), transitive, consistent and never true for null. Always take an Object parameter so you really override it.

Example code​

A correct equals method

class Email {
private final String address;

Email(String address) { this.address = address.toLowerCase(); }

@Override
public boolean equals(Object other) {
if (this == other) return true; // reflexive
if (!(other instanceof Email that)) return false; // handles null and other types
return address.equals(that.address);
}

@Override
public int hashCode() { return address.hashCode(); } // always override both together
}

class Demo {
public static void main(String[] args) {
Email a = new Email("Asha@Example.com");
Email b = new Email("asha@example.com");
System.out.println(a.equals(b));
System.out.println(b.equals(a)); // symmetric
System.out.println(a.equals(null)); // never true for null
System.out.println(a == b); // == compares identity, not value
}
}

// Output:
// true
// true
// false
// false

Finished this page? Track your progress (saved only in your browser).