我创建了一个名为 Idea 的简单类,其中包含 ColumnPositions 的 HashSet(我创建的另一个类仅使用 x 和 y 字段)。ColumnPosition 中的 equals 和 hashcode 方法如下所示:
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + x;
result = prime * result + y;
System.out.println("hashCode: " + result);
return result;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof ColumnPosition) {
ColumnPosition cp = (ColumnPosition) obj;
if (cp.x != this.x || cp.y != this.y) {
return false;
}
}
return true;
}
但是,当我去测试 Idea 类并尝试在 Idea 对象的 HashSet 中删除一个 ColumnPosition 对象时。它不起作用。怎么了??谢谢!
public void test_HashSetRemoveColumnPosition() {
ColumnPosition column_03 = new ColumnPosition(0, 3);
Set<ColumnPosition> columns = new HashSet<ColumnPosition>();
columns.add(column_03);
this.idea.getColumnPositions().add(column_03);
assertEquals(1, columns.size());
assertTrue(this.idea.getColumnPositions().remove(column_03)); // this is passing
assertEquals(0, columns.size()); // this is failing because columns.size() still equals 1. WHAT?! How is this possible if the remove method returned true?
}