April 09, 2011

Comparison Between Hashtable and HashMap in Java

The HashMap class is roughly equivalent to Hashtable. Both provide key-value access to data. The Hashtable is one of the original collection classes in Java. HashMap is part of the Java 2, v1.2. The key difference between the two is that access to the Hashtable is synchronized on the table while access to the HashMap isn't. You can add it, but it isn't there by default. Another difference is that iterator in the HashMap is fail-safe while the enumerator for the Hashtable isn't. If you change the map while iterating, you'll know. And, a third difference is that HashMap permits null values in it, while Hashtable doesn't.

So, if you your process is multi-threaded, then it's good idea to select Hashtable. 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.

One more, be careful with the class names, HashMap and Hashtable.

By the way, people tends to use HashMap rather than Hashtable. I don't know the reason, anyway, it's comfortable to use.