Why not allow an external interface to provide hashCode/equals for a HashMap?(为什么不允许外部接口为 HashMap 提供 hashCode/equals?)
问题描述
使用 TreeMap
提供自定义 Comparator
是很简单的,从而覆盖添加到地图的 Comparable
对象提供的语义.HashMap
s 然而不能以这种方式控制;提供散列值和相等性检查的函数不能被侧载".
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'.
我怀疑设计一个接口并将其改造成 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么不允许外部接口为 HashMap 提供 hashCode/equ


- Eclipse 插件更新错误日志在哪里? 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01