You want to be able to compare objects of your class.
equals( ) method.
How do you determine equality? For arithmetic or boolean operators,
the answer is simple: you test with the
object references, though, Java
== 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.
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
hashCode methods are
used by hashes
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
equals( ) properly.
Here are the rules for an
It is reflexive:
x.equals(x) must be true.
It is symmetric:
x.equals(y) must be true if and only if
y.equals(x) is also true.
It is ...