java HashCode无法检索条目

时间:2013-09-08 19:23:52

标签: java hashmap

我有一个我无法解决的错误。我的HashMap有一些条目,但我无法通过密钥检索它们。 键确实有hashCode和equals重写,但据我所知,它们工作正常。他们正在使用eclipse的生成器实现 以下代码证明了这个问题。 HashMap拒绝承认它包含自己提供的密钥。像get这样的其他方法也不起作用。

HashMap<SimpleTurn, Turn> turns = node.turns;
System.out.println("verifying HashMap turns"); 
System.out.println(" class : "+turns.getClass().getName()+" "+turns.getClass().getCanonicalName());
for(SimpleTurn sp : turns.keySet()){
    System.out.println("Am I equal to myself : "+sp.equals(sp));
    System.out.println("Do I belong to my collection : "+turns.containsKey(sp));
}

请注意,我明确地尝试检查我的equals的实现,它似乎工作正常。 上面代码的输出是:

verifying HashMap turns
class : java.util.HashMap java.util.HashMap
Am I equal to myself : true
Do I belong to my collection : false
Am I equal to myself : true
Do I belong to my collection : false
Am I equal to myself : true
Do I belong to my collection : false

此行为在整个代码中是一致的,可能导致此行为的原因是什么?我应该寻找的任何提示? 非常感谢你

1 个答案:

答案 0 :(得分:1)

只有当hashCode返回的内容与首次插入密钥时使用的值不同时,才会出现您所描述的行为。例如

public class Main {     
    public int count = 0;
    public static void main(String[] args) throws Exception {   //Read user input into the array
        HashSet<Main> set = new HashSet<>();
        Main main = new Main();
        main.count = 3;

        set.add(main);
        main.count = 2; // changes what hashCode() returns 

        System.out.println(set.contains(main)); // prints false
    }

    public int hashCode() {
        return count;
    }
}

HashSet在其底层实施中使用HashMap

密钥存储在由hashCode()的原始3值定义的位置。我们修改对象并尝试检查Set是否包含它。 contains()方法将再次调用hashCode()方法,返回2,并检查是否存在具有该值的元素(存储桶)。它找不到任何东西,因此返回false

在将对象添加到Map后,您必须修改作为密钥的对象。

相关问题