Alex Rivera | Logout

Why not allow an external interface to provide hashCode/equals for a HashMap?

Asked 2008-10-17T23:06:24.920
15

With a TreeMap it's trivial to provide a custom Comparator, thus overriding the semantics provided by Comparable objects added to the map. HashMaps however cannot be controlled in this manner; the functions providing hash values and equality checks cannot be 'side-loaded'.

I suspect it would be both easy and useful to design an interface and to retrofit this into HashMap (or a new class)? Something like this, except with better names:

  interface Hasharator<T> {
    int alternativeHashCode(T t);
    boolean alternativeEquals(T t1, T t2);
  }

  class HasharatorMap<K, V> {
    HasharatorMap(Hasharator<? super K> hasharator) { ... }
  }

  class HasharatorSet<T> {
    HasharatorSet(Hasharator<? super T> hasharator) { ... }
  }

The case insensitive Map problem gets a trivial solution:

 new HasharatorMap(String.CASE_INSENSITIVE_EQUALITY);

Would this be doable, or can you see any fundamental problems with this approach?

Is the approach used in any existing (non-JRE) libs? (Tried google, no luck.)

EDIT: Nice workaround presented by hazzen, but I'm afraid this is the workaround I'm trying to avoid... ;)

EDIT: Changed title to no longer mention "Comparator"; I suspect this was a bit confusing.

EDIT: Accepted answer with relation to performance; would love a more specific answer!

EDIT: There is an implementation; see the accepted answer below.

EDIT: Rephrased the first sentence to indicate more clearly that it's the side-loading I'm after (and not ordering; ordering does not belong in HashMap).

Edit
Report

1 Answer

0

There's such a feature in com.google.common.collect.CustomConcurrentHashMap, unfortunately, there's currently no public way how to set the Equivalence (their Hasharator). Maybe they're not yet done with it, maybe they don't consider the feature to be useful enough. Ask at the guava mailing list.

I wonder why it haven't happened yet, as it was mentioned in this talk over two years ago.

answered 2011-04-18T10:54:45.037

Your Answer