Hashtable in Java
The Hashtable class implements the Map interface and extends the Dictionary class. It implements a hash table which shows the key-value relation, i.e., it maps the keys to the values. Hashtable contains bucket (index) to store the key-value pair. The key’s hashcode is used to determine to which bucket the key-value pair should be mapped.
- Hashtable is similar to HashMap, but it is synchronized whereas HashMap is not.
- The object that is used as a key or as a value must not be null.
- For successful storing and fetching of the object from the Hashtable, the object must implement the hashcode() and the equals() methods.
- The hash function is used to get a bucket location from the key’s hashcode. A hash function always returns a number for an Object.
Let’s take the hashtable with & buckets :
The performance of the hashtable is affected by its two parameters, i.e., initial capacity and load factor.
Initial Capacity-The number of buckets in the hashtable denotes its capacity. And the initial capacity is the capacity at the time hashtable is created. If the initial capacity is larger than the maximum number of entries the hashtable then, the rehash operation will not occur. The tradeoff between wasted space and requirement of rehash operation is controlled by initial capacity.
Load Factor-It is a measure of space acquired by the hashtable that is allowed to get before its capacity is automatically increased.
If we need to insert a large number of entries into the hashtable, it is better to create it with large capacity. It allows the values to be inserted more efficiently than letting it to perform automatic rehashing as required to grow the table.