1. Memory Allocation

HashMap calls hashCode method on the key object and applies returned hash value to its own static hash function to find a bucket location where keys and values are stored in form of a nested class called Entry(Map.Entry)

Hashtable uses a hash function to compute an index into an array of buckets or slots, from which the desired value can be found.

Memory Allocation of HashMap
Memory Allocation of HashMap
Memory Allocation of Hashtable
Memory Allocation of Hashtable

2. Synchronization

HashMap is non-synchronized.

Hashtable is synchronized.

3. Thread Safety

Hashtable is thread-safe and can be shared between multiple threads.

HashMap can not be shared between multiple threads without proper synchronization.

4. Null keys and values

HashMap allows one null key and any number of null values.

Hashtable do not allow null keys and null values in the Hashtable object.

5. Iterating the values

HashMap object values are iterated by using an iterator.

Hashtable is the only class other than vector which uses an enumerator to iterate the values of Hashtable object.

6. Fail-fast iterator

The iterator in HashMap is fail-fast iterator while the enumerator for Hashtable is not.

HashMap iterator throw ConcurrentModificationException if any other Thread modifies the map structurally by adding or removing any element except Iterator’s own remove() method.

Enumerations returned by the Hashtable keys and element methods are not fail fast.

7. Performance

Because of thread-safety and synchronization Hashtable is much slower than HashMap if used in Single threaded environment.

HashMap would be the best option if we do not require a multi threaded environment.

HashMap does not guarantee that the order of the map will remain constant over time.

8. Superclass and Legacy

Hashtable is a subclass of Dictionary class which is now obsolete in JDK 1.7 hence it is not used anymore.

It is better off externally synchronizing a HashMap or using a ConcurrentMap implementation.

HashMap is the subclass of the AbstractMap class. Although Hashtable and HashMap has different superclasses but they both are implementations of the Map abstract data type.

9. Example of HashMap and Hashtable

hashmap: {DeltaX=Jerry, AlphaZ=Devin, Champ=Tom} hashtable: {AlphaZ=Devin, Champ=Tom, DeltaX=Jerry}

It's good to share...Share on FacebookTweet about this on TwitterShare on LinkedInPin on PinterestShare on Google+Email this to someone

Leave a Reply

Your email address will not be published. Required fields are marked *