Home » Core Java » Hashtable in Java

Hashtable in Java

Hashtable & its feature ::
1.  Hashtable class is an important class of Collection framework.
2.  Hashtable extends generic Dictionary.
3.  Hashtable implements generic Map, cloneable and java.io.Serializable interface.
4.  Hashtable class implements a hash table, which maps keys to values. Any non-null object can be used as a key or as a value.To successfully store and retrieve objects from a hashtable, the objects used as keys must implement the hashCode method and the equals method. An instance of Hashtable has two parameters that affect its performance: initial capacity(default 16) and load factor(deafult .75). The capacity is the number of buckets in the hash table, and the initial capacity is simply the capacity at the time the hash table is created. Note that the hash table is open: in the case of a “hash collision”, a single bucket stores multiple entries, which must be searched sequentially. The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased.The initial capacity and load factor parameters are merely hints to the implementation. The exact details as to when and whether the rehash method is invoked are implementation-dependent.Internal working of Hashtabl and HashMap are similiar.For Detail understanding Please see How does a HashMap work internally ?
5.By default Hashtable stores the elements in natural sorting order and it gives unique elements.
6.  Hashtable is synchronized i.e. it is thread safe.
7.Hashtable does not allow null key and null values.If you try to insert null key or value,you will get NullPointerException.
8. Hashtable implementation provides average O(1) time cost for the basic operations put(), get(),remove() and containsKey().
9.Hashtable uses Iterator interface to traverse the elements.While traversing the elements using iterator if the structure of the Hashtable is modified using remove method or re hashing of Hashtable is done,iterator will throw ConcurrentModificationException.So iterators for Hashtable are fail-fast.While iterating you can add new elements without getting ConcurrentModificationException.

Sample Program ::

Output ::

Now let us see an example of ConcurrentModificationException.In the below program while iterating the Hashtable,i am modifying the structure of the Hashtable by removing an element.So I am getting ConcurrentModificationException.
Example of ConcurrentModificationException ::

Output ::

Leave a comment

Your email address will not be published. Required fields are marked *

17 − thirteen =