Re: hashCode and equals (again)
Todd wrote:
Hello,
I have spent a great deal of time reading through the postings in this
group as well as tutorials/explanations on sites elsewhere (i.e.,
Roedy's, etc.), but have not been able to get a good grasp of hashCode
and equals. I understand most of the rules for hashCode are defined
for use of objects in maps and other comparable collections, so it is
from that POV that I am trying to get a good grasp of the concepts.
Please help if you can - especially the SCCE later.
1. Originally, I thought that it made sense to make an equals method
that uses hashCode as its criteria for equality. However, as I now
understand hashCode, the code _must_ be the same for equal objects,
BUT it is _possible_ to be the same for non-equal objects. Am I
stating this correctly?
Right. "Objects are equal" implies "hashCodes are equal,"
but not necessarily the other way around. Think about it a
bit and you'll see why this must be so: a hashCode is an int
value, and there are "only" four billion different ints. Since
there are far, far more than four billion different Strings,
for example, they can't all have unique hashCodes; some Strings
that are different will have the same hashCode and are said
to "collide."
2. When would one use a set of criteria to determine equality that is
different from the criteria used to generate a hashCode?
Rarely. You might have a class with several elements that
must agree if two instances are considered "equal," but perhaps
it would be inconvenient or expensive to compute hashCodes for
some of those elements. If so, you might decide to omit them
from your class' hashCode computation (although you would still
need to test their equality in your equals method). Usually,
though, it is advisable to include all the equality-determining
elements in the hashCode computation.
Note that the hashCode must *not* depend on anything that
is not part of the equality determination! Can you see why?
3. Why aren't the hashCode_s in the following code the same?
[... hashCodes of arrays with identical content ...]
That's just the way Java is defined: two distinct arrays
are not "equal" just because they happen to have identical
content. One reason for this is that two arrays that have
the same content at one moment could have different content
a moment later; this would be inconvenient if the arrays were
already in a HashMap or in a Set or something. The Arrays
class provides static methods you can use if you want content-
based notions of equals and hashCode.
--
Eric.Sosman@sun.com