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:
It is reflexive:
x.equals(x)
must be true.It is symmetric:
x.equals(y)
must be true if and only ify.equals(x)
is also true.It is ...
Get Java Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.