简体   繁体   中英

Removing HashSet with Object

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.

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

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