hashCode() (which is used for
java.util.TreeMap to name a few) has the following implementation:
int hashValue = 0; for(final Iterator i=entrySet().iterator(); i.hasNext(); ) hashValue += i.next().hashCode();
(This is noted in the javadoc for
If you have a significant number of entries in your
HashMap then you’re going to get bit computing the hash code. Performance gets even worse if the entries in the map are complex.
I would recommend subclassing and overriding
hashCode() (with adequate documentation explaining the reasons for overriding as well as outlining the computation for the new value!) if you find yourself in a sticky performance situation. A more sane hash code might be:
int hashValue = 0; for(final Iterator i=keySet().iterator(); i.hasNext(); ) hashValue += i.next().hashCode();
as it is common to use simple types for the keys of a map. The use of
keySet() preserves the:
If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.
If you’re jamming a
HashMap into another map to meet the constraints of some interface (as is common in web programming) it may be even better to simply use
size() as the hash code to minimize the performance impact.
Don’t forget that you’re still going to get hit with the
equals() (which is a full pass over the entry set) each time that you retrieve the
HashMap from the enclosing map.