Hashmap and Hashtable

  • 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). However, HashMap can be synchronized using
Map m = Collections.synchronizeMap(hashMap);
  • Hashtable and HashMap are member of the Java Collections Framework (since Java 2 platform v1.2, Hashtable was retrofitted to implement the Map interface).
  • Hashtable is considered legacy code, the documentation advise to use ConcurrentHashMap in place of Hashtable if a thread-safe highly-concurrent implementation is desired.
  • HashMap doesn’t guarantee the order in which elements are returned. In a Hashtable, the elements are placed in a (seemingly) chaotic order based on the hashcode of the key thus, when you iterate over a Hashtable, there will indeed be an order. But as far as you can tell, it’s completely arbitrary and can change in apparently random ways as the collection changes.
Key Differences
 HashMap  HashTable
 HashMap is non synchronized  Hashtable is synchronized
 HashMap can contain one null key and null values.  HashTable can only contain non-null object as a key or as a value.
The iterators returned by Map are fail-fast, if the map is structurally modified at any time after the iterator is created, in any way except through the iterator’s own remove method, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.   The Enumerations returned by Hashtable’s keys and elements methods are not fail-fast.

source : stackoverflow
Rate this post

Leave a Reply