Re: hashCode
On 8/28/12 5:02 PM, markspace wrote:
On 8/28/2012 4:33 PM, Daniel Pitts wrote:
interface Hasher<Type> {
int hash(Type t);
Not really seeing how this is a good idea. How would you implement this?
So, that would change HashMap to take a Hasher<? super K> instance in
its constructor.
This is the problem; Map (and HashMap) were desired to be spec'd as
taking Object, not a subclass.
Actually, they are Generic, so they are not spec'd to take Object, but
to take a specific subtype defined at compile time. At least, now that
they have the addition of Generics. Pre-generics, they still had
Comparators which had the same behavior that I'm describing, but instead
of defining buckets, they define an ordering. See below.
A default Hasher<Object> could be implemented to use
System.identityHashCode and == for the common use-case.
Again not seeing how you'd actually use that to put an object in a Map.
Example usage:
++++
// MyKeyHasher implements Hasher<MyKey>
Map<MyKey, MyValue> map=new HashMap<MyKey,MyValue>(new MyKeyHasher());
map.put(myFirstKey, myFirstValue);
map.put(mySecondKey, mySecondValue);
++++
This is directly analogous to how TreeMap and Comparator currently work
together:
++++
Map<MyKey, MyValue> map =
new TreeMap<MyKey, MyValue(new MyKeyComparator());
map.put(myFirstKey, myFirstValue);
map.put(mySecondKey, mySecondValue);
++++
Now, it would be my opinion that the standard library should provide a
IdentityHasher implementation as such:
++++
public final class IdentityHasher<T> implements Hasher<T> {
public int hash(T object) {
return System.identityHashCode(object);
}
public boolean isEqual(T l, T r) {
return l == r;
}
}
++++
There could of course be a singleton instance of this, similar to how
they have a singleton for Collections.emptySet();
Does that make more sense?