Java Reference
In-Depth Information
each entry with the hash value of the desired element. Only if the two hash values are equal does
the implementation check the elements for equality. This optimization makes sense because it is
usually much cheaper to compare hash codes than elements.
Because of this optimization, it is not enough for the hash set to search in the right bucket; the two
Name instances must have equal hash values in order for the hash set to recognize them as equal.
The odds that the program prints TRue are therefore the odds that two consecutively created objects
have the same identity hash code. A quick experiment showed these odds to be about one in
25,000,000. Results may vary depending on which Java implementation is used, but you are highly
unlikely to see the program print TRue on any JRE we know of.
To fix the problem, simply add an appropriate hashCode method to the Name class. Although any
method whose return value is determined solely by the first and last name will satisfy the contract, a
high-quality hash function should attempt to return different hash values for different names. The
following method will do nicely [EJ Item 8]. Once this method is added, the program will print
true as expected:
public int hashCode() {
return 37 * first.hashCode() + last.hashCode();
}
In summary, always override hashCode when you override equals . More generally, obey the
general contract when you override a method that has one. This is an issue for most of the non-final
methods declared in Object [ EJ Chapter 3]. Failure to follow this advice can result in arbitrary,
unspecified behavior.
 
 
Search WWH ::




Custom Search