开发者

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 regul开发者_运维知识库ar 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.


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() {
   }
}


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.


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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜