简体   繁体   中英

Removing a user defined object in a HashSet in Java

I have created a simple class called Idea with a HashSet of ColumnPositions(another class I created with just an x and y field) . The equals and hashcode method in ColumnPosition looks like this:

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

However, when I go to test the Idea class and try to remove a ColumnPosition object within the HashSet of the Idea object. It doesn't work. What's wrong?? Thanks!

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是同一对象。

You have 2 hashsets: the local variable in your test and a field in your test class. They are not the same so when you remove from one, the other is not modified...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM