O'Reilly logo

Java Cookbook by Ian F. Darwin

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Overriding the Equals Method

Problem

You want to be able to compare objects of your class.

Solution

Write an equals( ) method.

Discussion

How do you determine equality? For arithmetic or boolean operators, the answer is simple: you test with the equals operator (==). For object references, though, Java provides both == and the equals( ) method inherited from java.lang.Object. The equals operator can be confusing, as it simply compares two object references to see if they refer to the same object. This is not what you want most of the time.

The inherited equals( ) method is also not as useful as you might imagine. Some people seem to start their life as Java developers thinking that the default equals( ) will magically do some kind of detailed, field-by-field or even binary comparison of objects. But it does not compare fields! It just does the simplest possible thing: it returns the value of an == comparison on the two objects involved! So, for anything useful, you will probably have to write an equals method. Note that both the equals and hashCode methods are used by hashes (Hashtable, HashMap; see Section 7.7). So if you think somebody using your class might want to create instances and put them into a hash, or even compare your objects, you owe it to them (and to yourself!) to implement equals( ) properly.

Here are the rules for an equals( ) method:

  1. It is reflexive: x.equals(x) must be true.

  2. It is symmetric: x.equals(y) must be true if and only if y.equals(x) is also true.

  3. It is ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required