The Java Course provides a general introduction to programming in Java. It is based on A.B. Downey's book, How to Think Like a Computer Scientist. Click here for details.

The equals Method

When you use the == operator to compare two objects, what you are really asking is, "Are these two things the same object?" That is, do both objects refer to the same location in memory.

For many types, that is not the appropriate definition of equality. For example, two complex numbers are equal if their real parts are equal and their imaginary parts are equal.

When you create a new object type, you can provide your own definition of equality by providing an object method called equals. For the Complex class, this looks like:

  public boolean equals (Complex b) {
    return (real == b.real && imag == b.imag);

By convention, equals is always an object method. The return type has to be boolean.

The documentation of equals in the Object class provides some guidelines you should keep in mind when you make up your own definition of equality:

The equals method implements an equivalence relation:

  • It is reflexive: for any reference value x, x.equals(x) should return true.
  • It is symmetric: for any reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
  • It is transitive: for any reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.
  • It is consistent: for any reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false.
  • For any reference value x, x.equals(null) should return false.

The definition of equals I provided satisfies all these conditions except one. Which one? As an exercise, fix it.

Last Update: 2011-01-24