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

前端 未结 9 1826
闹比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 16:01

    I suspect this has not been done because it would prevent hashCode caching?

    I attempted creating a generic Map solution where all keys are silently wrapped. It turned out that the wrapper would have to hold the wrapped object, the cached hashCode and a reference to the callback interface responsible for equality-checks. This is obviously not as efficient as using a wrapper class, where you'd only have to cache the original key plus one more object (see hazzens answer).

    (I also bumped into a problem related to generics; the get-method accepts Object as input, so the callback interface responsible for hashing would have to perform an additional instanceof-check. Either that, or the map class would have to know the Class of its keys.)

提交回复
热议问题