Skip to Main Content
Java Cookbook
book

Java Cookbook

by Ian F. Darwin
June 2001
Intermediate to advanced content levelIntermediate to advanced
888 pages
21h 1m
English
O'Reilly Media, Inc.
Content preview from Java Cookbook

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Practical Cloud-Native Java Development with MicroProfile

Practical Cloud-Native Java Development with MicroProfile

Emily Jiang, Andrew McCright, John Alcorn, David Chan, Alasdair Nottingham
Distributed Computing in Java 9

Distributed Computing in Java 9

Raja Malleswara Rao Malleswara Rao Pattamsetti

Publisher Resources

ISBN: 0596001703Supplemental ContentCatalog PageErrata