Java HashMap containsKey始终为false [英] Java HashMap containsKey always false

查看:888
本文介绍了Java HashMap containsKey始终为false的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个有趣的情况,我将 Coordinate 存储到 HashMap< Coordinate,GUIGameField> 中。

现在,奇怪的是,我有一段代码,应该防范,不应该使用两次坐标。但是,如果我调试此代码:

$ $ p $ $ code if(mapForLevel.containsKey(coord)){
throw new IllegalStateException(这个坐标已经被使用了!);
} else {
... do stuff ...
}

... containsKey 总是返回 false ,尽管我将一个散列码为9731的坐标存储到map和当前coord也有hashcode 9731。



之后, mapForLevel.entrySet()看起来像:

 (java.util.HashMap $ EntrySet)[(270,90)=gui.GUIGameField@29e357,(270, 90)= gui.GUIGameField@ca470] 

我可能做错了什么?我用完了想法。感谢您的帮助!

  public class Coordinate {
int xCoord;
int yCoord;

公共坐标(int x,int y){
...存储参数属性...
}

... getters& amp ; setters ...

@Override
public int hashCode(){
int hash = 1;
hash = hash * 41 + this.xCoord;
hash = hash * 31 + this.yCoord;
返回散列;



$ div $解析方案

你除了 hashCode 之外,还应该覆盖 equals 以使其正常工作。

编辑:我错误地指出你应该在 equals 中使用 hashCode code> - 这是不正确的。虽然 hashCode 必须为两个相等的对象返回相同的结果,但仍可能为不同的对象返回相同的结果。

I have the funny situation, that I store a Coordinate into a HashMap<Coordinate, GUIGameField>.

Now, the strange thing about it is, that I have a fragment of code, which should guard, that no coordinate should be used twice. But if I debug this code:

if (mapForLevel.containsKey(coord)) {
    throw new IllegalStateException("This coordinate is already used!");
} else {
    ...do stuff...
}

... the containsKey always returns false, although I stored a coordinate with a hashcode of 9731 into the map and the current coord also has the hashcode 9731.

After that, the mapForLevel.entrySet() looks like:

(java.util.HashMap$EntrySet) [(270,90)=gui.GUIGameField@29e357, (270,90)=gui.GUIGameField@ca470]

What could I have possibly done wrong? I ran out of ideas. Thanks for any help!

public class Coordinate {
    int xCoord;
    int yCoord;

    public Coordinate(int x, int y) {
        ...store params in attributes...
    }

    ...getters & setters...

    @Override
    public int hashCode() {
        int hash = 1;
        hash = hash * 41 + this.xCoord;
        hash = hash * 31 + this.yCoord;
        return hash;
    }
}

解决方案

You should override equals in addition to hashCode for it to work correctly.

EDIT : I have wrongly stated that you should use hashCode in your equals - this was not correct. While hashCode must return the same result for two equal objects, it still may return the same result for different objects.

这篇关于Java HashMap containsKey始终为false的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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