1. Overall structure of container:

Both the key and value of a HashMap can be null. When a HashMap encounters a null key, putForNullKey is invoked to process it, but value is not processed.

Neither key nor value of a Hashtable can be null. When Hashtable encounters null, NullPointerException is returned.

2. Capacity setting and expansion mechanism:

By default, the initial capacity of a HashMap is 16, and the capacity of the container must be 2 to the power of n. When the container is expanded, it is twice the original capacity.

By default, the initial capacity of a Hashtable is 11. During capacity expansion, the capacity of a Hashtable is doubled and then increased by 1. Int newCapacity = (oldCapacity << 1) + 1; .

3. Hash distribution (calculating storage location) :

HashMap is to obtain the hash value after the hashCode of the key key is disturbed by the perturbation function, and then use **hash & (Length-1)** instead of modulo to obtain the storage location of the element.

Hashtable is divided by remainder (since its default size is not 2 to the n). Int index = (hash & 0x7fffff) % tab.length; .

Since the container capacity of HashMap must be 2 to the power of n, the method of hash & (Length-1) can be used to calculate the position of elements instead of taking modulus to improve the operation efficiency. However, the container capacity of Hashtable is not necessarily 2 to the power of N, so this method cannot be used instead.

4. Thread safety (most important) :

A HashMap is not thread-safe and can be made thread-safe by calling synchronizedMap(Map

m). However, it is inefficient to use, so it is recommended to use ConcurrentHashMap to achieve thread-safety.
,v>

Hashtable is thread-safe, with synchronized modifier before each operation method, but it is not efficient to run. Therefore, it is recommended to use ConcurrentHashMap to achieve thread-safe operation.

Therefore, Hashtable is a legacy container, and it is recommended to use HashMap if we do not need thread synchronization, or ConcurrentHashMap if thread synchronization is required.