We will find out answers for following question
- What is Hashtable
- Common methods available
- HashTable is a member of Java Collection Framework as it implements Map Interface.
- HashTable 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 and load factor.
- 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.
- The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased.
Hashtable is fail fast
If the Hashtable is structurally modified at any time after the iterator is created, in any way except through the iterator’s own remove method, the iterator will throw a ConcurrentModificationException
htable.clear(); => Clears this hashtable so that it contains no keys. htable.containsKey(12); => Returns true if and only if the specified object is a key in this hashtable, as determined by the equals method; false otherwise. htable.containsValue("Hello"); => Returns true if this map maps one or more keys to the specified value htable.getOrDefault(12, "No Value"); => Returns the value to which the specified key is mapped, or defaultValue if this map contains no mapping for the key htable.size(); => Returns int the number of key-value mappings in this map . If the map contains more than Integer.MAX_VALUE elements, returns Integer.MAX_VALUE. htable.isEmpty(); => Returns true if this map contains no key-value mappings htable.replace(12, "test"); => Replaces the entry for the specified key only if it is currently mapped to some value. htable.put(1, "Hello"); => Returns the previous value of the specified key in this hashtable, or null if it did not have one
Note: Hashtable is synchronized. So if we look into methods like isEmpty() or put() we will find synchronized block
- If a thread-safe implementation is not needed, it is recommended to use HashMap in place of Hashtable.
- If a thread-safe highly-concurrent implementation is desired, then it is recommended to use ConcurrentHashMap in place of Hashtable.