Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HashSet with two equals object?

Tags:

java

hashset

I created an object HashSet, and the value is an object (Triple) which is my own class. But I get a strange thing, when there are two equal objects on my HashSet, is it possible? Here is my overriding method for the equals in the class Triple

 @Override
 public boolean equals(Object other){
 if (other == null) return false;
 if (other == this) return true;
 if (this.getClass() != other.getClass()) return false;
 Triple otherTriple = (Triple)other;

 if(otherTriple.getSubject().equals(getSubject()) &&
   otherTriple.getPredicate().equals(getPredicate()) &&
   otherTriple.getObject().equals(getObject()))
  return true;
 return false;

}

like image 908
zfm Avatar asked Dec 17 '22 20:12

zfm


1 Answers

You need to be sure to implement hashCode() as well, and when two Triples are equal, their hashCodes must also be equal. If you don't do that, you will get strange behavior.

like image 113
Eric Bowman - abstracto - Avatar answered Dec 19 '22 08:12

Eric Bowman - abstracto -