【问题标题】:Java - Map.remove not actually removing [duplicate]Java - Map.remove 实际上并未删除[重复]
【发布时间】:2019-08-22 22:44:41
【问题描述】:

我有一个带有私有成员 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 实现。您是否按照需要覆盖了hashCode
  • 如果使用HashMap....(hashCode()(然后equals)用于定位元素)

标签: java oop dictionary collections equals


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2011-02-25
    • 2014-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-19
    • 1970-01-01
    • 1970-01-01
    • 2019-04-03
    相关资源
    最近更新 更多