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

前端 未结 9 1851
闹比i
闹比i 2020-12-17 15:28

With a TreeMap it\'s trivial to provide a custom Comparator, thus overriding the semantics provided by Comparable objects added to the

9条回答
  •  悲哀的现实
    2020-12-17 15:54

    A bit late for you, but for future visitors, it might be worth knowing that commons-collections has an AbstractHashedMap (in 3.2.2 and with generics in 4.0). You can override these protected methods to achieve your desired behaviour:

    protected int hash(Object key) { ... }
    protected boolean isEqualKey(Object key1, Object key2) { ... }
    protected boolean isEqualValue(Object value1, Object value2) { ... }
    protected HashEntry createEntry(
        HashEntry next, int hashCode, Object key, Object value) { ... }
    

    An example implementation of such an alternative HashedMap is commons-collections' own IdentityMap (only up to 3.2.2 as Java has its own since 1.4).

    This is not as powerful as providing an external "Hasharator" to a Map instance. You have to implement a new map class for every hashing strategy (composition vs. inheritance striking back...). But it's still good to know.

提交回复
热议问题