Java is analysed in the Map with a HashMap Hashtable the difference between HashSet

  • 2020-04-01 02:17:58
  • OfStack

The difference between HashTable and HashMap

First, the inherited parent is different.
Hashtable is derived from the Dictionary class, while HashMap is derived from the AbstractMap class. But both implement the Map interface.


public class Hashtable<K,V>
extends Dictionary<K,V>
implements Map<K,V>, Cloneable, Serializable
public class HashMap<K,V>
extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable

Second, thread safety is different.
The method in Hashtable is Synchronize, while the method in HashMap is non-synchronize by default. In the context of multithreaded concurrency, you can use Hashtable directly without synchronizing its methods, but you must add your own synchronization when using HashMap.

Third, whether the contains method is provided
HashMap removes the contains method from the Hashtable and changes it to containsValue and containsKey, because the contains method is misleading.

Hashtable retains the contains, containsValue, and containsKey methods, which contain the same function as containsValue.

Fourth, whether null values are allowed for key and value.
Where the key and value are both objects and cannot contain duplicate keys, but can contain duplicate values.
Null values are not allowed for both key and value in the Hashtable.
In a HashMap, null can be used as a key, so there is only one key; There can be one or more keys that correspond to a value of null. When the get() method returns a null value, it is possible that the key is not in the HashMap, or that the value corresponding to the key is null. Therefore, instead of the get() method in a HashMap determining whether a key exists in a HashMap, use the containsKey() method.

Fifth, the internal implementation of the two traversal methods is different.
Both Hashtable and HashMap use iterators. For historical reasons, Hashtable also USES an Enumeration method.

Sixth, different hash values.
HashTable directly USES the hashCode of the object. A HashMap recalculates the hash value.

Seventh, the internal implementation USES different array initialization and expansion methods.
The initial size and expansion of the two internally implemented arrays, Hashtable and HashMap. The default size of the hash array in HashTable is 11, and the increment is old*2+1.

The default size of the hash array in a HashMap is 16, and it must be an exponent of 2.


Related articles: