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