Java Reference
In-Depth Information
TRue
when it finds a key of the same value in the table. For example, the
String
class overrides
equals
to return
TRue
if the two
String
objects have
the same contents. It also overrides
hashCode
to return a hash based on
the contents of the
String
so that two strings with the same contents
have the same
hashCode
.
The term
identity
is used for reference equality: If two references are
identical, then
==
between the two will be
true
. The term
equivalence
describes value equalityobjects that may or may not be identical, but
for which
equals
will return
true
. So one can say that the default imple-
mentation of
equals
is that equivalence is the same as identity. A class
that defines a broader notion of equality can have objects that are not
identical be equivalent by overriding
equals
to return
TRue
based on the
states of the objects rather than their identities.
Some hashtables, such as
java.util.IdentityHashMap
, are concerned with
identity of objects, not equivalence. If you need to write such a hasht-
able, you want hash codes corresponding to the identity of objects, not
their states. The method
System.identityHashCode
returns the same value
that the
Object
class's implementation of
hashCode
would return for an
object if it were not overridden. If you simply use
hashCode
on the ob-
jects you are storing, you might get a hash code based on equivalence,
not on identity, which could be far less efficient.
Exercise 3.7
: Override
equals
and
hashCode
for
ColorAttr
.