I was trying to debug my code which uses a
HashSet and searching through the SO, I found out that I needed to override the
hashCode method as well. The strange part is, checking the related API, I did not see any part in it mentioning about the
hashCode method. Quoting the definition of the
add method of
HashSet as seen in the API:
public boolean add(E e)
Adds the specified element to this set if it is not already present. More formally, adds the specified element e to this set if this set contains no element e2 such that (e==null ? e2==null : e.equals(e2)). If this set already contains the element, the call leaves the set unchanged and returns false.
Now in the quotation above, I don't see anywhere that mentions about the
hashCode method. Shouldn't the correct statement have been like:
... if this set contains no element e2 such that (e==null ? e2==null : e.equals(e2)) AND if this set contains no element e2 such that (e==null ? e2==null : e.hashCode() == e2.hashCode()).
Now if you say that: "If
o1.equals(o2) returns true,
o2.hashCode() MUST evaluate to true as well.", then I would ask three questions:
Where is that fact specified? (in general, or in the API)
Even if that fact is specified somewhere, where in the API it is specified that
HashSetmakes use of the
If that fact is indeed correct, why isn't the compiler enforces overriding the
hashCodemethod, whenever the
equalsmethod is overridden?