HashTable, HashMap, HashSet come with a raft of gnarly problems for the unwary developer to do with the way keys are represented.  When adding new items and looking up an item, Java expects (quite correctly) to have the following overridden method on the Object that is the key:

Method

Description

hashCode()

By default produces a value generated on the reference address.  This means that two Objects that have the same logical key (yet in different areas of memory) will not match in a map or set.  So if you want two objects to be treated as logically the same when put in a hashmap or set, this hashcode() function needs to return the same information for both.  If not overridden, the two objects won't match.

It's easy to get this working correctly by implementing a new hashcode() function, but historically few do it well.  So new developers please note the following tip.

Tip: If in doubt, always use Strings as a hashing key because they implement hashcode() correctly for use in maps and sets.

blog comments powered by Disqus