Search code examples
javahashmap

Java : How to check if a key is exists in a Hashmap


I have defined a hashmap of type :

HashMap<Position, Double> list = new HashMap<>();

Where Position is class with two attributes x and y .

I would like to verify if a position is already in the list or not, I have tried this :

public void addToList(Position p, double somme) {
    if (this.list.containsKey(p)) {
        this.list.replace(p, this.list.get(p) + somme);//add the old value somme 
    } else {
        this.list.put(p, somme);
    }
}

I think I should be more specific and verify values of x any y instead of check if key is exist because each time the check failed to detect an exist position.

How can check if a position is in the list or not?


Solution

  • You should override the equals and hashCode methods of your Position object so that two elements with the same value for x and y are equals.

    @Override
    public boolean equals(Object obj) { 
        if (obj == this) {
            return true;
        }
        if (obj == null || obj.getClass() != this.getClass()) {
            return false;
        }
    
        Position otherPos = (Position) obj;
        return x == otherPos.x
                && y == otherPos.y;
    }
    
    @Override
    public int hashCode() {
        return Objects.hash(x, y);
    }