【发布时间】:2013-02-08 23:00:40
【问题描述】:
我认为我的问题很简单,但是我找不到解决方案,所以我决定在这里提问。我需要的是使用这样的自定义密钥类型制作HashMap:
HashMap<Pair<Integer, Integer>, StrategyPoint> myMap = new HashMap<Pair<Integer, Integer>, StrategyPoint> ();
但是我在这里遗漏了一些东西,因为HashMap 停止正常工作。首先,密钥变得不唯一,并且可以在keySet 中找到具有相同值的 Pair 的不同实例。包含键功能也不能像我想象的那样工作:)。
我显然错过了一些东西,更有可能我应该以某种方式定义一种方法来比较我的 Pair 类中的实例。但是,我尝试在 Pair 类中使用 compareTo 实现 Comparable ,但它仍然无法正常工作。有什么建议吗?
我的原始代码有点乱,不友好,所以我在这里做了一个例子来说明我的问题。
代码如下:
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 中找到它。
【问题讨论】: