【发布时间】:2019-08-22 22:44:41
【问题描述】:
我有一个带有私有成员 x 和 y 的 Vector2d 对象。
它具有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