Java Reference
In-Depth Information
ȗ If
x.equals(y)
, then
x.hashCode() == y.hashCode()
After all, if
x
and
y
are
equal
to each other, then you don't want to insert both of
them into a setȌsets don't store duplicates. But if their hash codes are different,
x
and
y
may end up in different buckets, and the
add
method would never notice that
they are actually duplicates.
Your
hashCode
method must be compatible with the
equals
method.
Of course, the converse of the compatibility condition is generally not true. It is
possible for two objects to have the same hash code without being equal.
For the
Coin
class, the compatibility condition holds. We define two coins to be
equal to each other if their names and values are equal. In that case, their hash codes
will also be equal, because the hash code is computed from the hash codes of the
name
and
value
fields.
You get into trouble if your class defines an
equals
method but not a
hashCode
method. Suppose we forget to define a
hashCode
method for the
Coin
class. Then
it inherits the hash code method from the
Object
superclass. That method computes
a hash code from the memory location of the object. The effect is that any two objects
are very likely to have a different hash code.
Coin coin1 = new Coin(0.25, "quarter");
Coin coin2 = new Coin(0.25, "quarter");
Now
coin1.hashCode()
is derived from the memory location of
coin1
, and
coin2.hashCode()
is derived from the memory location of
coin2
. Even though
coin1.equals(coin2)
is
true
, their hash codes differ.
However, if you define neither
equals
nor
hashCode
, then there is no problem.
The
equals
method of the
Object
class considers two objects equal only if their
memory location is the same. That is, the
Object
class has compatible
equals
and
hashCode
methods. Of course, then the notion of equality is very restricted: Only
identical objects are considered equal. That is not necessarily a bad notion of equality:
If you want to collect a set of coins in a purse, you may not want to lump coins of
equal value together.
716
717