The difference between HashMap and HashTable is often asked by others. Let’s summarize it here today.
(1) The history of inheritance is different
public class Hashtable extends Dictionary implements Map
public class HashMap extends AbstractMap implements Map
Copy after login
## Hashtable is inherited from the Dictionary class, while HashMap was introduced in Java 1.2 An implementation of the Map interface.
(2) Different security
HashMap is non-synchronized, while HashTable is synchronized by default, which means that HashTable is thread-safe and multiple threads can share a HashTable; Without proper synchronization, multiple threads cannot share a HashMap. Java 5 and later provides ConcurrentHashMap, which is a replacement for HashTable and has better scalability than HashTable. Of course, we can synchronize HashMap through the following methods:
Map m = Collections.synchronizeMap(hashMap);
Copy after login
(3) Similarities and differences of whether the value can be null
HashMap allows you to use null values as a table The key or value of the entry. Only one record in a HashMap can be an empty key, but any number of entries can be an empty value. That is to say, if the search key is not found in the table, or if the search key is found, but it is an empty value, then get() will return null; but not in HashTable, null values are not allowed in key and value. .
(4) The internal implementation of the traversal methods between the two is different
Both Hashtable and HashMap use Iterator, and HashMap’s Iterator (Iterator) is a fail-fast iterator, while HashTable's enumerator iterator is not fail-fast. Due to historical reasons, Hashtable also uses Enumeration.
(5) The use of hash values is different
HashTable directly uses the hashCode of the object, while HashMap needs to recalculate the hash value.
(6) The initial size of the array and the expansion method of the internal implementation of the two are different
The default size of the hash array in HashTable is 11, and the increasing method is old*2+1; HashMap The default size of the hash array is 16, and it must be an exponent of 2.
Thank you for reading, I hope it can help you, thank you for your support of this site!
For more detailed explanations of the differences between java HashMap and HashTable, please pay attention to the PHP Chinese website!