What's the difference between HashMap and Hashtable?
Yes, there is a Hashtable class in Java.
Right, Hashtable with a lowercase t.
1. First difference. They inherit from different classes.
Right, Hashtable with a lowercase t.
1. First difference. They inherit from different classes.
Hashtable is based on Dictionary class. HashMap is implemented based on the Map interface since Java 1.2. See the code below.
public class HashMap<K, V> extends AbstractMap<K, V> implements Cloneable, Serializable {...}
public class Hashtable<K, V> extends Dictionary<K, V> implements Map<K, V>, Cloneable, Serializable {...}
HashMap extends the abstract class AbstractMap and implement the Map interface:
public abstract class AbstractMap<K, V> implements Map<K, V> {...}
2. The methods in Hashtable are synchronized,but the methods in HashMap are not synchronized by default. In multi-thread situations,we can use Hashtable. If we choose to use HashMap, we need to handle the synchronization.
3. In Hashtable, no null value for keys (nullPointerException will be thrown). In HashMap, we can have at most one null key.
4. Different implementations on Iteration. Hashtable and HashMap both use Iterator. However, Hashtable also uses Enumeration to iterate the items.
5. Different way to hash. HashTable uses hashCode of the object. But HashMap will re-calculate the hash value.
6. Different strategies to resize. In HashTable, the initial size hash array is 11. The resizing formula is old*2+1. In HashMap, the hash array is 16. It is guaranteed that the size is power of two.
2. The methods in Hashtable are synchronized,but the methods in HashMap are not synchronized by default. In multi-thread situations,we can use Hashtable. If we choose to use HashMap, we need to handle the synchronization.
3. In Hashtable, no null value for keys (nullPointerException will be thrown). In HashMap, we can have at most one null key.
4. Different implementations on Iteration. Hashtable and HashMap both use Iterator. However, Hashtable also uses Enumeration to iterate the items.
5. Different way to hash. HashTable uses hashCode of the object. But HashMap will re-calculate the hash value.
6. Different strategies to resize. In HashTable, the initial size hash array is 11. The resizing formula is old*2+1. In HashMap, the hash array is 16. It is guaranteed that the size is power of two.
Comments
Post a Comment