Thursday, September 5, 2013

Difference between HashMap and HashTable?

Difference between HashMap:

                  Both HashMap and Hashtable implements Map interface but there are some significant difference between them which is important to remember before deciding whether to use HashMap or Hashtable in Java. Some of them is thread-safetysynchronization and speed.
                   1.The HashMap class is roughly equivalent to Hashtable, except that it is non synchronized and permits nulls. (HashMap allows null values as key and value whereas Hashtable doesn't allow nulls).

                          2. 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 can not be shared between multiple threads without proper synchronization.

                   3.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.

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


sources: http://javarevisited.blogspot.in/2010/10/difference-between-hashmap-and.html




HashMap can be synchronized by

Map m = Collections.synchronizeMap(hashMap);


No comments:

Post a Comment