Removing HashSet with Object

70 views Asked by At

When I try to remove a HashSet that takes an object, the hashset.contains(Object) and iterator.equals(Object) are always false, even when they should be true.

public boolean removeElement(Element element)
{        
    Iterator<Element> itr = elements.iterator();
    while (itr.hasNext()) {
        Element oldElement = itr.next();
        if (itr.equals(new Element(element.eString, element.eInt, element.eBoolean))) {
            itr.remove();
            return true;
        }
        if (elements.contains(new Element(element.eString, element.eInt, element.eBoolean))) {
            elements.remove(new Element(element.eString, element.eInt, element.eBoolean));
            return true;
        }
    }
    return false;
}

Is this a feature of Java, a bug, or am I simply coding this wrong? This seems like the logical solution to removing, but it always fails without throwing any errors.

1

There are 1 answers

3
M A On BEST ANSWER
itr.equals(new Element(element.eString, element.eInt, element.eBoolean))

This will always return false because you're comparing an Iterator to an Element which are completely different types of objects. You want to compare the element to itr.next() which you have saved previously to a local variable.

if (elements.contains(new Element(element.eString, element.eInt, element.eBoolean))) {

This would return false as well if you didn't override the equals() method in the class Element. The default Object.equals() method is used which dictates that the two references should refer to the same object in order to be equal. In this case, you're comparing against a new object that you create using new Element(element.eString, element.eInt, element.eBoolean). To solve this you need to override the equals method to specify how the objects of type Element must be checked for equality.

For example, if Element has the following fields:

String eString;
int eInt;
boolean eBoolean;

Then you can override equals as follows:

@Override
public boolean equals(Object obj) {
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if (getClass() != obj.getClass())
        return false;
    Element other = (Element) obj;
    if (eBoolean != other.eBoolean)
        return false;
    if (eInt != other.eInt)
        return false;
    if (eString == null) {
        if (other.eString != null)
            return false;
    } else if (!eString.equals(other.eString))
        return false;
    return true;
}