mP.
mP.

Reputation: 18266

Java: Need a hash Map where one supplies a function to do the hashing

I would like to know of a Map that works like a regular HashMap/Hashtable except it takes a function which returns the hashcode and performs the equality test rather than letting the HashMap use Object.hashCode/equals.

I cant use TreeMap because the objects do not implement Comparable and there is no stable way to handle the case of unequal objects. One cannot use System.identityHashCode because there is the potential for conflicts for objects that are not equal.

Ideally it would be great if the Map took a function in a similar way one can supply a custom Comparator to a TreeMap rather than letting the TreeMap cast parameters to Comparable.

The only way around this problem is to wrap each key and have the wrapper do the custom hashing/equals but surely therse a better way.

Upvotes: 20

Views: 7584

Answers (5)

William Jarvis
William Jarvis

Reputation: 357

As other answers suggest wrapping your objects with an object with the desired hashCode and equals is generally the best way to go. If on the rare case you want the function to be to use the original equals and hashCode implementation on Object there actually is IdentityHashMap for that very use case. However I appreciate the function you want is likely something than this.

Upvotes: 1

mernst
mernst

Reputation: 8117

Plume-lib's WeakHasherMap does what you want: its constructor takes as an argument a Hasher object, which defines a hashCode() method and an equals() method.

(This existed at the time you wrote your question, but I only noticed your question now, 6.5 years after you asked it.)

Edit: I am a maintainer of plume-lib.

Upvotes: 3

Harv
Harv

Reputation: 79

When using TreeMap, the objects in the map are not required to implement Comparable.

Upvotes: 1

Paŭlo Ebermann
Paŭlo Ebermann

Reputation: 74760

I proposed an interface for such a "hash function" some time ago.

Now you need to take any implementation of a hash map (The OpenJDK one is GPL, for example) and modify all calls of hashCode() and .equals() with calls to this hash object. I did this once (many years ago), but it is not published.

Upvotes: 0

Jochen Bedersdorfer
Jochen Bedersdorfer

Reputation: 4122

Did you consider a simple wrapper around the objects you would like to cache?

class Wrapper {
   YourObject object;

   public boolean equals(Object someOther) {
   ...
   }
   public int hashCode() {
   }
}

Upvotes: 10

Related Questions