如何使 HashMap 与自定义键类型一起正常工作?

How to make HashMap work properly with custom key type?(如何使 HashMap 与自定义键类型一起正常工作?)

本文介绍了如何使 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 类上正确实现 equalshashCode.

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 与自定义键类型一起正常工作?

基础教程推荐