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
基础教程推荐
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- 降序排序:Java Map 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01