Happy Happy Joy Joy (was: On to Hydro)
Dan Bornstein
danfuzz@milk.com
Wed, 23 Aug 2000 10:56:56 -0700 (PDT)
I wrote:
>I agree strongly with that sentiment. I don't know how many times
>the java.util collection classes have p'ed me off because I couldn't
>just tell them to compare (and hash) with a different function.
Tyler Close writes:
>My RedBlackTree does use a configurable comparison predicate (where
>this whole thread started from), but my Hashtable does not support a
>separate hashing function. Could you explain why you would want one?
Glibly, because I want to compare by something other than the default
equality, and equality and hashing functions come in pairs.
The main recurring situation that I run into with java.util is that
I want to construct an identity hashtable (that is, that compares with
== and therefore uses System.identityHashCode).
The other usual scenario is where I have no control over defining equals()
and hashCode() on the objects I'm using as keys (e.g., they are instances
of String) and I'd like to do something special (such as do
case-insensitive lookups).
The case that came up recently in my past had to do with garbage-generation
and/or synchronization concerns. I had a table of string-like-things which
I wanted to be able to look up using strings directly, rather than
allocating a new string-like-thing. Unfortunately, the contract for Map
doesn't say whether a key in the table or the key being looked up is the
target for equals() comparisons. That is, if the map contains key1 and I
say "map.get (key2)", I have no way of knowing whether the implementation
will perform "key1.equals(key2)" or "key2.equals(key1)". If it always did
the former, then I could arrange for the equals method on my
string-like-things to accept a String as an argument, but unfortunately, I
can't count on that happening. But in that case, I'd be restricted to
defining the hashCode on my string-like-things to be the same as the String
hashCode (something I don't necessarily want to do). The two options,
neither particularly appetizing, are (1) always allocate and initialize a
new string-like-thing when doing lookups or (2) keep a temporary and
mutable string-like-thing around to do lookups and synchronize access to
it. I opted for option 2 (the garbage issue was the worse problem in the
application in question), but I really want the third option of just
specifying external equality and hashing functions.
-dan