Java HashMap containsKey always false

Posted by Dennis on Stack Overflow See other posts from Stack Overflow or by Dennis
Published on 2012-10-14T15:29:20Z Indexed on 2012/10/14 15:37 UTC
Read the original article Hit count: 237

Filed under:
|
|

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;
    }
}

© Stack Overflow or respective owner

Related posts about java

Related posts about hashmap