为什么不允许外部接口为HashMap提供hashCode / equals? [英] Why not allow an external interface to provide hashCode/equals for a HashMap?

查看:203
本文介绍了为什么不允许外部接口为HashMap提供hashCode / equals?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 TreeMap ,提供自定义 Comparator 很重要,因此覆盖了 Comparable 对象添加到地图中。 然而,HashMap 无法以这种方式控制;提供哈希值和相等性检查的函数不能被侧面加载。



我怀疑设计一个接口是很容易和有用的, code> HashMap (或一个新类)?这样的东西,除了更好的名字:

  interface Hasharator< T& {
int alternativeHashCode(T t);
boolean alternativeEquals(T t1,T t2);
}

class HasharatorMap< K,V> {
HasharatorMap(Hasharator<?super K> hasharator){...}
}

class HasharatorSet& {
HasharatorSet(Hasharator< ;? super T> hasharator){...}
}


$ b b

不区分大小写的地图 问题得到一个平凡的解决方案:

  new HasharatorMap(String.CASE_INSENSITIVE_EQUALITY); 

这是否可行,或者你能看到这种方法的任何根本问题吗?



在任何现有(非JRE)库中使用的方法? (尝试google,没有运气。)



编辑:hazzen提供的好的解决方法,但恐怕这是解决方法我想避免...; )



编辑:将标题更改为不再提及Comparator;我怀疑这有点混乱。



编辑:与表现相关的接受答案;会喜欢更具体的答案!



编辑:有一个实现;请参阅下面接受的答案。



编辑:改动第一个句子,以表明更清楚,这是侧装载我之后(而不是排序;



他们的地图有一个具有不同限制的实现,并且因此不同的先决条件,因此这并不隐含意味着Java的本地HashMap的实现将是可行的。


With a TreeMap it's trivial to provide a custom Comparator, thus overriding the semantics provided by Comparable objects added to the map. HashMaps 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<T> {
    int alternativeHashCode(T t);
    boolean alternativeEquals(T t1, T t2);
  }

  class HasharatorMap<K, V> {
    HasharatorMap(Hasharator<? super K> hasharator) { ... }
  }

  class HasharatorSet<T> {
    HasharatorSet(Hasharator<? super T> hasharator) { ... }
  }

The case insensitive Map 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).

解决方案

Trove4j has the feature I'm after and they call it hashing strategies.

Their map has an implementation with different limitations and thus different prerequisites, so this does not implicitly mean that an implementation for Java's "native" HashMap would be feasible.

这篇关于为什么不允许外部接口为HashMap提供hashCode / equals?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆