Class below implements a hash table, which maps keys to values. Any non-null object is used as a key or as a value.
The objects used as keys must implement the hashCode method and the equals method, in order to successfully store and retrieve objects from a hashtable,
public class Hashtable
, Cloneable, Serializable
This is Hash table based implementation of the Map interface. This implementation provides all of the optional map operations. It also permits the null key and null values.
(The HashMap class is almost equivalent to Hashtable, with major difference being that it is unsynchronized and also permits nulls.)
This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.
public class HashMap
, Cloneable, Serializable
K - the type of keys maintained by this map
V - the type of mapped values
Map is an interface; HashMap is a particular implementation of that interface. HashMap uses a collection of hashed key values to do its lookup.
• HashMap and Hashtable both are data structures
• Both store data in key and value form.
• Both use hashing technique to store unique keys.
• Hashtable was part of the original java.util and is a concrete implementation of a Dictionary. However, Java 2 re-engineered Hashtable so that it also implements the Map interface.
• HashMap inherits AbstractMap class whereas Hashtable inherits Dictionary class.
• HashMap allows one null key and multiple null values, while the Hashtable doesn't allow any null key or value.
• The hashmap cannot have the duplicate keys in it that is why there keys must only be mapped with only the single value. But the hashtable allows the duplicate keys in it.
• The hashmap contains an iterator which is basically fail-safe but the hashtable contains an enumerator, which is not fail-safe.
• The access to hashtable is synchronized on the table while the access to the hashmap is not synchronized.
• HashMap is fast as compared to Hashtable which is slow.
• HashMap is traversed by Iterator but Hashtable is traversed by Enumerator and Iterator.
• HashMap is non synchronized. It is not-thread safe and can't be shared between many threads without proper synchronization code but Hashtable is synchronized. It is thread-safe and can be shared with many threads.
We can make the HashMap as synchronized by calling this code
Map m = Collections.synchronizedMap(hashMap) but Hashtable is internally synchronized and can't be unsynchronized.
• Iterator in HashMap is fail-fast wheras Enumerator in Hashtable is not fail-fast.