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.

Advertisements

One Response to “Java Hashmap or Hashtable”

  1. Hi,
    While discussing about HashMap its worth mentioning following questions which frequently asked in Java interviews now days like How HashMap works in Java or How get() method of HashMap works in JAVA very often. on concept point of view these questions are great and expose the candidate if doesn’t know deep details.

    Javin
    FIX Protocol tutorial

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

 
%d bloggers like this: