How to make HashMap work properly with custom key type?(如何使 HashMap 与自定义键类型一起正常工作?)
问题描述
我认为我的问题很简单,但是我找不到解决方案,所以我决定在这里提问.我需要的是用这样的自定义键类型制作一个 HashMap
:
I think my question is quite simple, however I couldn't find the solution so I decided to ask here. What i need is to make a HashMap
with a custom Key type like this:
HashMap<Pair<Integer, Integer>, StrategyPoint> myMap = new HashMap<Pair<Integer, Integer>, StrategyPoint> ();
但是我在这里遗漏了一些东西,因为 HashMap
停止正常工作.首先,Key 变得不唯一,并且可以在 keySet
中找到具有相同值的不同 Pair 实例.包含键功能也不能像我想象的那样工作:).
However I am missing something here, because the HashMap
stops working properly. First the Key becomes not unique and a different instances of Pair with same values can be found in the keySet
. Also the contains key function does not work the way I suppose it to :).
我显然错过了一些东西,更有可能我应该以某种方式定义一种方法来比较我的 Pair
类中的实例.但是,我尝试在我的 Pair
类中使用 compareTo
实现 Comparable,但它仍然无法正常工作.有什么建议吗?
I clearly miss something and more likely I should somehow define a way to compare my instances from my Pair
class. However I tried implementing Comparable with compareTo
in my Pair
class and it still don't work. Any suggestions?
我的原始代码有点凌乱且不友好,所以我在这里做了一个例子来说明我的问题.
My original code is kinda messy and unfriendly to read, so I made an example just to illustrate my problem here.
代码如下:
HashMap<Pair<Integer, Integer>, StrategyPoint> myMap = new HashMap<Pair<Integer, Integer>, StrategyPoint> ();
Pair<Integer, Integer> myPair = new Pair<Integer, Integer>(2,2);
StrategyPoint myPoint= new StrategyPoint(2, 2, 5, 5, false);
myMap.put(myPair, myPoint);
Pair<Integer, Integer> searcher = new Pair<Integer, Integer> (0,0);
searcher.setFirst(2);
searcher.setSecond(2);
System.out.println(myMap.containsKey(searcher));
System.out.println(myMap.containsKey(myPair));
执行的结果是:
false
true
我已经对其进行了调试,并且搜索器实例已正确填充,但是 HashMap
似乎拒绝在其 keySet
中找到它.
I have debug it and the searcher instance is being populated properly, however it seems the HashMap
refuse to find it in its keySet
.
推荐答案
您必须在 Pair
类上正确实现 equals
和 hashCode
.
You must implement properly equals
and hashCode
on the Pair
class.
HashMap
使用这些方法来区分和散列键类.
The HashMap
uses these methods to differentiate and hash the key class.
这篇关于如何使 HashMap 与自定义键类型一起正常工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使 HashMap 与自定义键类型一起正常工作?
- C++ 和 Java 进程之间的共享内存 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01