0

I have a Vector2d object with private members x and y. It has the equals function:

@Override
public boolean equals(Object o) {
    if (!(o instanceof Vector2d))
        return false;
    Vector2d other = (Vector2d) o;
    return this.x == other.getX() && this.y == other.getY();
}

I have a Map<Vector2d, Tile> and I want to remove any entry that has a certain position. Here's my method where I want to do that:

public void placeTile(Tile tile, double tileX, double tileY) {
    Vector2d pos = new Vector2d(tileX, tileY);
    // overwrite
    this.tiles.remove(pos);
    for (Vector2d v : new HashSet<>(this.tiles.keySet())) {
        if (pos.equals(v))
            this.tiles.remove(v);
    }
    this.tiles.put(new Vector2d(tileX, tileY), tile);
}

Now the odd thing is that this.tiles.remove(pos) does not work - it doesn't actually remove the Tile with that position. However, the loop works. Any ideas what could cause this behavior? It is like the HashMap is not using the implemented equals. Thank you

MCMastery
  • 3,099
  • 2
  • 20
  • 43

1 Answers1

3

You need to override hashCode() as well as equals() as the HashMap indexes keys using the hashcode.

    @Override
    public int hashCode() {
        return Objects.hash(x, y);
    }
Marc G. Smith
  • 876
  • 6
  • 8