Re: hashCode
On Monday, August 27, 2012 5:03:37 PM UTC-7, markspace wrote:
Daniel Pitts wrote:
I find it somewhat disappointing that there are Comparable/Comparator
interfaces, but no Hashable/Hasher interfaces.
I think -- I'm not sure, but I believe -- the the ability to hash
something into a hash table (a symbol table, in some terminologies) was
considered so important and so fundamental to so many algorithms that it
was deemed intrinsic to the system. And therefore mandated for all objects.
Right or wrong, that's plausible.
And a separate Hasher interface would be kludgey.
For example, in C, one can always hash based on memory address. In Java
we don't have that option, so hashCode() takes the place of the
intrinsic property of an address.
That really makes sense. We have a nearly unique code for every object, and
in practical terms one is vanishingly unlikely to get duplicate identity hashes
within any given run.
Whereas the ability to sort or order objects was recognized as not being
intrinsic to all objects, so it was separated out. Sorting a list, or
ordering a tree, isn't something you can always do by default.
Just my two nickels here, and of course I'm guessing as to why
hashcode() is included in Object and not an interface.
So to cap this topic, we have a default identity hash in the 'Object#hashCode()'
implementation that does a good job of distributing things in 'HashMap' and
the like, and matches the semantics of the default identity 'equals()'. The OP's
question as to whether one should substitute the degenerate hash gets a
resounding "NO!" One overrides 'hashCode()' for consistency with 'equals()'
exactly when the latter is overridden. If the type in question implements
'Comparable' then the 'compareTo()' method likewise should match, as should
'toString()' (in a somewhat looser sense of "match", perhaps, but not too loose).
All four methods speak to the semantics of sameness for the type in question,
and should be consistent with each other.
--
Lew