如何使用自定义键类型使HashMap正常工作? [英] How to make HashMap work properly with custom key type?

查看:142
本文介绍了如何使用自定义键类型使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 类中使用 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 类上的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正常工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆