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

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

问题描述

使用 TreeMap 提供自定义 Comparator 是很简单的,从而覆盖添加到地图的 Comparable 对象提供的语义.HashMaps 然而不能以这种方式控制;提供散列值和相等性检查的函数不能被侧载".

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'.

我怀疑设计一个接口并将其改造成 HashMap(或一个新类)既简单又有用?像这样的东西,除了更好的名字:

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

不区分大小写的 Map 问题得到了一个简单的解决方案:

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?

是否在任何现有(非 JRE)库中使用了该方法?(试过谷歌,没有运气.)

Is the approach used in any existing (non-JRE) libs? (Tried google, no luck.)

hazzen 提出了很好的解决方法,但恐怕这是我试图避免的解决方法...... ;)

Nice workaround presented by hazzen, but I'm afraid this is the workaround I'm trying to avoid... ;)

将标题更改为不再提及比较器";我怀疑这有点令人困惑.

Changed title to no longer mention "Comparator"; I suspect this was a bit confusing.

接受与性能相关的答案;希望得到更具体的答案!

Accepted answer with relation to performance; would love a more specific answer!

有一个实现;请参阅下面接受的答案.

There is an implementation; see the accepted answer below.

改写第一句以更清楚地表明这是我所追求的侧载(而不是排序;排序不属于 HashMap).

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具有我所追求的功能,他们称之为散列策略.

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

他们的地图具有不同的限制和不同的先决条件的实现,因此这并不隐含地意味着 Java 的本机"HashMap 的实现是可行的.

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天全站免登陆