Java Reference
In-Depth Information
Overriding the equals() and hashCode() Methods
Problem
You want to be able to compare objects of your class and/or use these objects reliably in
Maps and other Collection s.
Solution
Outfit your class with an equals() and hashCode() method.
Discussion
How do you determine equality? For arithmetic or Boolean operands, 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 because it simply compares two object references to see if they refer to the same
object. This is not the same as comparing the objects themselves.
The inherited equals() method is also not as useful as you might imagine. Some people
seem to start their lives as Java developers thinking that the default equals() magically does
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 == compar-
ison on the two objects involved! So, for any value classes you write, you probably have to
write an equals method. [ 29 ] Note that both the equals and hashCode methods are used by
Map s or hashes ( Hashtable , HashMap ; see Mapping with Hashtable and HashMap ) . So if you
think somebody using your class might want to create instances and put them into a Map , or
even compare your objects, you owe it to them (and to yourself!) to implement both
equals() and hashCode() , and to implement them properly. The Eclipse IDE (see Compil-
ing, Running, and Testing with an IDE ) offers a Source menu item “Generate hashCode()
and equals()”—it will only do both at the same time, not let you generate equals() without
hashCode() nor vice versa.
equals()
Here are the rules for a correct equals() method:
 
Search WWH ::




Custom Search