java - Removing HashSet with Object -
when try remove hashset
takes object, hashset.contains(object)
, iterator.equals(object)
false, when should 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 feature of java, bug, or coding wrong? seems logical solution removing, fails without throwing errors.
itr.equals(new element(element.estring, element.eint, element.eboolean))
this always return false because you're comparing iterator
element
different types of objects. want compare element itr.next()
have saved local variable.
if (elements.contains(new element(element.estring, element.eint, element.eboolean))) {
this return false if didn't override equals()
method in class element
. default object.equals()
method used dictates 2 references should refer same object in order equal. in case, you're comparing against new object create using new element(element.estring, element.eint, element.eboolean)
. solve need override equals
method specify how objects of type element
must checked equality.
for example, if element
has following fields:
string estring; int eint; boolean eboolean;
then can override equals
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; }
Comments
Post a Comment