java哈希代码无法检索条目

java哈希代码无法检索条目,java,hashmap,Java,Hashmap,我有一个无法解决的错误。我的HashMap有一些条目,但我无法通过键检索它们。 这些键确实覆盖了hashCode和equals,但据我所知,它们工作得很好。他们使用eclipse的生成器实现 下面的代码证明了这个问题。HashMap拒绝承认它包含自己提供的密钥。其他方法如get也不起作用 HashMap<SimpleTurn, Turn> turns = node.turns; System.out.println("verifying HashMap turns"); Syste

我有一个无法解决的错误。我的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));
}
这种行为在整个代码中是一致的,什么可能导致这种行为?对我应该寻找的东西有什么提示吗?
非常感谢

只有当您的
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;
    }
}
公共类主{
公共整数计数=0;
publicstaticvoidmain(字符串[]args)向数组中抛出异常{//Read用户输入
HashSet=newhashset();
Main Main=新Main();
main.count=3;
集合。添加(主);
main.count=2;//更改hashCode()返回的内容
System.out.println(set.contains(main));//打印错误
}
公共int hashCode(){
返回计数;
}
}
HashSet
在其底层实现中使用
HashMap

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


您必须在将键添加到
映射后修改作为键的对象

在hashmap中输入键后是否修改了键?您的hashcodes可能正在更改。请向我们显示您的hashCode和equals代码