The difference between javaHashMap and HashTable

  • 2020-05-26 08:23:03
  • OfStack

The difference between HashMap and HashTable is often asked.

(1) different history of inheritance


public class Hashtable extends Dictionary implements Map
public class HashMap extends AbstractMap implements Map

Hashtable is an inheritance from the Dictionary class, while HashMap is an implementation of the Map interface introduced by Java 1.2.

(2) different security

HashMap is not synchronized, while HashTable is synchronized by default, which means HashTable is thread safe and multiple threads can share one HashTable. Multiple threads cannot share HashMap without proper synchronization. ConcurrentHashMap is available after Java 5, which is an alternative to HashTable and has better scalability than HashTable. Of course, we can synchronize HashMap by:


Map m = Collections.synchronizeMap(hashMap);

(3) similarities and differences between null values

HashMap allows you to use null values as key or value for 1 table entry. Only one record in HashMap can be an empty key, but any number of entries can be empty value. That is, if no search key is found in the table, or if a search key is found, but it is an empty value, get() will return null; HashTable does not. key and value do not allow null values.

(4) the two are different in the internal implementation of the traversal mode

Both Hashtable and HashMap use Iterator iterators. HashMap's iterator (Iterator) is fail-fast's iterator, while HashTable's enumerator iterator is not fail-fast's. For historical reasons, Hashtable also USES Enumeration.

(5) different hash values are used

HashTable directly USES the hashCode of the object, while HashMap needs to recalculate the hash value.

(6) the initial size and expansion of the array of the internal realization mode of 2 are different

The default size of hash array in HashTable is 11, and the increment is old*2+1; The default size of the hash array in HashMap is 16, and 1 must be an exponent of 2.

Thank you for reading, I hope to help you, thank you for your support of this site!


Related articles: