Developer/Designer Notes

Java Hashmap or Hashtable

Posted by Kiran Mova on March 8, 2007

How do I choose between Hashmap or Hashtable in java? Here are some questions that will help.

(a) Is my process multi-threaded? If yes, Hashtable is the choice since it is thread-safe. However there is a way of making Hashmaps thread safe using Collections.synchronizedMap(new Hashmap() ). If my Java version is 1.5 or higher, then I have the option of using ConcurrentHashMap.

(b) What is the data-type of my keys? It seems like when the keys are a set of integers, Hashtable has better performance. Check this thread at java forum: Hashtable Vs HashMap

Note: The Hashtable is not part of the Java Collections Framework. But it does support all the API that a Collection interface specifies. Hashtable is what the Sun calls, the legacy collection implementation. Hashtable inherits from the Dictionary class which is obsolete in Java 1.6, while the HashMap inherits from collection interface “Map”.

If you are using Java 1.6, it might be a good idea to check the latest additions to the Map implementations like NavigableMap. (Navigable is a misleading name, which makes me think of google maps.) But the operations that it provides to extract a subset of entries based on satisfying criterion is pretty cool.

Update 04/09 : Iterating through values of Hashtable in Java6.

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <pre> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>