我创建了一个名为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?
}

最佳答案

确保this.idea.getColumnPositions()columns是同一对象。

09-13 05:48