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

With a `TreeMap` it's trivial to provide a custom `Comparator`, thus overriding the semantics provided by `Comparable` objects added to the map. `HashMap`s however cannot be controlled in this manner; the functions providing hash values and equality checks cannot be 'side-loaded'. I suspect it would be both easy and useful to design an interface and to retrofit this into `HashMap` (or a new class)? Something like this, except with better names: interface Hasharator { int alternativeHashCode(T t); boolean alternativeEquals(T t1, T t2); } class HasharatorMap { HasharatorMap(Hasharator hasharator) { ... } } class HasharatorSet { HasharatorSet(Hasharator hasharator) { ... } } The [case insensitive `Map`][1] problem gets a trivial solution: new HasharatorMap(String.CASE_INSENSITIVE_EQUALITY); Would this be doable, or can you see any fundamental problems with this approach? Is the approach used in any existing (non-JRE) libs? (Tried google, no luck.) EDIT: Nice workaround presented by hazzen, but I'm afraid this is the workaround I'm trying to avoid... ;) EDIT: Changed title to no longer mention "Comparator"; I suspect this was a bit confusing. EDIT: Accepted answer with relation to performance; would love a more specific answer! EDIT: There is an implementation; see the accepted answer below. EDIT: Rephrased the first sentence to indicate more clearly that it's the side-loading I'm after (and not ordering; ordering does not belong in HashMap). [1]: https://stackoverflow.com/questions/212562/is-there-a-good-way-to-have-a-mapstring-get-and-put-ignore-case
"This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time." -- HashMap's Javadocs. In other words, HashMap isn't ordered.

以上就是Why not allow an external interface to provide hashCode/equals for a HashMap?的详细内容,更多请关注web前端其它相关文章!

赞(0) 打赏
未经允许不得转载:web前端首页 » JavaScript 答疑

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

前端开发相关广告投放 更专业 更精准

联系我们

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏