What is HashMap?
The HashMap class uses a hash table to store the card, providing a fast execution time for the
put() queries for large sets. The class implements the
Map interface (data storage in the form of key / value pairs). Keys and values can be of any type, including
null. All keys must necessarily be unique, and the values can be repeated. This implementation does not guarantee the order of the elements.
// K - Key, V - Value class HashMap<K, V>
You can declare it as follows:
Map<String, Integer> hashMap = new HashMap<String, Integer>(); Map<String, String> hashMap = new HashMap<String, String>();
What is Hashtable?
Hashtable class implements a hashtable, which maps keys to values. It inherits Dictionary class and implements the Map interface.
Main Hashtable features:
- A Hashtable is an array of list. Each list is known as a bucket. The position of bucket is identified by calling the
hashcode()method. A Hashtable contains values based on the key.
- It contains only unique elements.
- It may have not have any null key or value.
- It is synchronized.
Differences between HashMap and Hashtable
After our research, we've found out that there are 3 main differences:
Hashtableis synchronized, and
HashMapis not. Due to this fact,
HashMapis better for non-threaded applications, as unsynchronized Objects typically perform better than synchronized ones.
Hashtabledoes not allow
nullkeys or values and
nullkey and any number of
One of HashMap's subclasses is
LinkedHashMap, so in the event that you'd want predictable iteration order (which is insertion order by default), you could easily swap out the
LinkedHashMap. This wouldn't be as easy if you were using