Re: hashCode
On 8/28/12 9:19 AM, markspace wrote:
On 8/28/2012 1:06 AM, Patricia Shanahan wrote:
On 8/27/2012 9:19 PM, markspace wrote:
I think System.identityHashCode() is the (same as the) default
implementation for Object::hashCode(), yes?
Yes, but it could have been written, with a slightly different
explanation, without putting hashCode() in Object.
And then you get into situations like this:
if( object instanceof Hasher )
hash = ((Hasher) o).hashCode();
else
hash = System.identityHashCode( object );
And I think we all know to use polymorphism instead here. This is kind
of what I'm saying. The usefulness of a hash code was consider
intrinsic to any object, and they wanted to avoid the code above.
Therefore, Object::hashCode() becomes the design spec.
The polymorphism shouldn't have been on the object itself, Think about
how TreeSet needs either Comparable objects, or a Comparator.
interface Hasher<Type> {
int hash(Type t);
boolean isEqual(Type l, Type r);
}
So, that would change HashMap to take a Hasher<? super K> instance in
its constructor. A default Hasher<Object> could be implemented to use
System.identityHashCode and == for the common use-case.
This allows you to define different hashes and equality for the same set
of object classes. It also forces you to implement hash and isEqual
together.
It is, however, too late to "fix" the language in this way.