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.
This will always return false because you're comparing an
Iterator
to anElement
which are completely different types of objects. You want to compare the element toitr.next()
which you have saved previously to a local variable.This would return false as well if you didn't override the
equals()
method in the classElement
. The defaultObject.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 usingnew Element(element.eString, element.eInt, element.eBoolean)
. To solve this you need to override theequals
method to specify how the objects of typeElement
must be checked for equality.For example, if
Element
has the following fields:Then you can override
equals
as follows: