When does HashSet 'add' method calls equals? [duplicate]
Solution 1:
If the hash codes differ, there is no need to call equals()
since it is guaranteed to return false
.
This follows from the general contract on equals()
and hashCode()
:
If two objects are equal according to the
equals(Object)
method, then calling thehashCode
method on each of the two objects must produce the same integer result.
Right now your class is breaking that contract. You need to fix that.
Solution 2:
If you want equals()
to be called always, just always return, say, 0
in hashCode()
. This way all items have the same hash code and are compared purely with equals()
.
public int hashCode() {
return 0;
}