The difference between HashTable and HashMap
First, the inherited parent classes are different.
Hashtable inherits from Dictionary class, while HashMap inherits from AbstractMap class. But both implement the Map interface.
Copy the code code as follows:
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 methods in Hashtable are Synchronized, while the methods in HashMap are non-Synchronized by default. In a multi-threaded concurrent environment, you can use Hashtable directly without synchronizing its methods yourself. However, when using HashMap, you must add synchronization processing yourself.
Third, whether to provide the contains method?
HashMap removed the contains method of Hashtable and changed it to containsValue and containsKey, because the contains method is easily misleading.
Hashtable retains three methods: contains, containsValue and containsKey, among which contains and containsValue have the same functions.
Fourth, whether key and value allow null values.
The key and value are both objects and cannot contain duplicate keys, but they can contain duplicate values.
In Hashtable, null values are not allowed in both key and value.
In HashMap, null can be used as a key, and there is only one such key; there can be one or more keys whose corresponding value is null. When the get() method returns a null value, it may be that the key does not exist in the HashMap, or the value corresponding to the key may be null. Therefore, in HashMap, the get() method cannot be used to determine whether a certain key exists in the HashMap, but the containsKey() method should be used to determine.
Fifth, the internal implementation of the two traversal methods is different.
Both Hashtable and HashMap use Iterator. Due to historical reasons, Hashtable also uses Enumeration.
Sixth, the hash values are different.
The use of hash values is different. HashTable directly uses the hashCode of the object. And HashMap recalculates the hash value.
Seventh, the internal implementation uses different array initialization and expansion methods.
The initial size and expansion methods of arrays in the two internal implementations of Hashtable and HashMap. The default size of the hash array in HashTable is 11, and the increasing method is old*2+1.
The default size of the hash array in HashMap is 16, and it must be an exponent of 2.