What are the differences between a HashMap and a Hashtable in Java?
Which is more efficient for non-threaded applications?
Keep in mind that HashTable
was legacy class before Java Collections Framework (JCF) was introduced and was later retrofitted to implement the Map
interface. So was Vector
and Stack
.
Therefore, always stay away from them in new code since there always better alternative in the JCF as others had pointed out.
Here is the Java collection cheat sheet that you will find useful. Notice the gray block contains the legacy class HashTable,Vector and Stack.
In addition to what izb said, HashMap
allows null values, whereas the Hashtable
does not.
Also note that Hashtable
extends the Dictionary
class, which as the Javadocs state, is obsolete and has been replaced by the Map
interface.
HashMap
: An implementation of the Map
interface that uses hash codes to index an array.
Hashtable
: Hi, 1998 called. They want their collections API back.
Seriously though, you're better off staying away from Hashtable
altogether. For single-threaded apps, you don't need the extra overhead of synchronisation. For highly concurrent apps, the paranoid synchronisation might lead to starvation, deadlocks, or unnecessary garbage collection pauses. Like Tim Howland pointed out, you might use ConcurrentHashMap
instead.
Beside all the other important aspects already mentioned here, Collections API (e.g. Map interface) is being modified all the time to conform to the "latest and greatest" additions to Java spec.
For example, compare Java 5 Map iterating:
for (Elem elem : map.keys()) {
elem.doSth();
}
versus the old Hashtable approach:
for (Enumeration en = htable.keys(); en.hasMoreElements(); ) {
Elem elem = (Elem) en.nextElement();
elem.doSth();
}
In Java 1.8 we are also promised to be able to construct and access HashMaps like in good old scripting languages:
Map<String,Integer> map = { "orange" : 12, "apples" : 15 };
map["apples"];
Update: No, they won't land in 1.8... :(
Are Project Coin's collection enhancements going to be in JDK8?
There are 5 basic differentiations with HashTable and HashMaps.
HashMap: It is a class available inside java.util package and it is used to store the element in key and value format.
Hashtable: It is a legacy class which is being recognized inside collection framework.