Friday 22 August 2014

5 main differences between HashTable and HashMap

HashMap and Hashtable both implement java.util.Map interface but there are some differences that Java developers must understand to write more efficient code.

1)One of the major differences between HashMap and Hashtable is that HashMap is non-synchronized whereas Hashtable is synchronized, which means Hashtable is thread-safe and can be shared between multiple threads but HashMap cannot be shared between multiple threads without proper synchronization. 

2)The HashMap class is roughly equivalent to Hashtable, except that it permits nulls. (HashMap allows null values as key and value whereas Hashtable doesn’t allow nulls).

3) The third significant difference between HashMap vs Hashtable is that Iterator in the HashMap is a fail-fast iterator while the enumerator for the Hashtable is not and throw ConcurrentModificationException if any other Thread modifies the map structurally by adding or removing any element except Iterator’s own remove() method. But this is not a guaranteed behavior and will be done by JVM on best effort. This is also an important difference between Enumeration and Iterator in Java.

4)One more notable difference between Hashtable and HashMap is that because of thread-safety and synchronization Hashtable is much slower than HashMap if used in Single threaded environment. So if you don’t need synchronization and HashMap is only used by one thread, it out perform Hashtable in Java.

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

Note that HashMap can be synchronized by
Map m = Collections.synchronizedMap(hashMap);
    You might like :
    Static varibale,static class,Static method

    No comments:

    Post a Comment