java.util.AbstractMap‘s hashCode() (which is used for java.util.HashMap and java.util.TreeMap to name a few) has the following implementation:

int hashValue = 0;
for(final Iterator i=entrySet().iterator(); i.hasNext(); )
hashValue +=;

(This is noted in the javadoc for java.util.AbstractMap.)

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 +=;

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.

contract of hashCode().

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.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s