Java - Map.remove 实际上没有删除

Java - Map.remove not actually removing

我有一个包含私有成员 xyVector2d 对象。 它具有 equals 功能:

@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();
}

我有一个 Map<Vector2d, Tile>,我想删除任何具有特定位置的条目。这是我想要执行此操作的方法:

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

现在奇怪的是 this.tiles.remove(pos) 不起作用 - 它实际上并没有删除那个位置的 Tile。但是,循环有效。 有什么想法会导致这种行为吗?就像 HashMap 没有使用已实现的 equals。谢谢

您需要覆盖 hashCode() 以及 equals(),因为 HashMap 使用哈希码对键进行索引。

    @Override
    public int hashCode() {
        return Objects.hash(x, y);
    }