Last Updated: 28 May, 2022
Hashtable is a legacy class in Java. It was introduced in the JDK 1.0 version and is available in the java.util package.
Hashtable stores the data in the form of key-value pairs, where keys must be unique and values may be duplicates.
Hashtable does not allow null as a key or value. If we add NULL as a key or value, then at runtime it will throw a NullPointerException.
Hashtable is by default a synchronised class in Java.
As we can see from the complete hierarchy above, Hashtable extends the Dictionary class and implements Map, Serializable, and Cloneable interfaces.
Here, K is the key Object type and V is the value Object type.
Output
Iterating Hashtable and printing Key and Value
700 - Python
400 - C
200 - C++
100 - Java
Constructor | Description |
---|---|
Hashtable() | Constructs a new, empty hashtable with a default initial capacity (11) and load factor (0.75). |
Hashtable(int initialCapacity) | Constructs a new, empty hashtable with the specified initial capacity and default load factor (0.75). |
Hashtable(int initialCapacity, float loadFactor) | Constructs a new, empty hashtable with the specified initial capacity and the specified load factor. |
Hashtable(Map<? extends K,? extends V> t) | Constructs a new hashtable with the same mappings as the given Map. |
The Hashtable class in java has the following methods.
Methods with Description |
---|
V put(K key, V value) It inserts the specified key and value into the hash table. |
void putAll(Map m)) It inserts all the elements of Map m into the invoking Hashtable. |
V putIfAbsent(K key, V value) If the specified key is not already associated with a value associates it with the given value and returns null, else returns the current value. |
V getOrDefault(Object key, V defaultValue) It returns the value associated with given key; or defaultValue if the hashtable contains no mapping for the key. |
V get(Object key) It returns the value associated with the given key. |
Enumeration keys() Returns an enumeration of the keys of the hashtable. |
Set keySet() Returns a set view of the keys of the hashtable. |
Collection values() It returns a collection view of the values contained in the Hashtable. |
Enumeration elements() Returns an enumeration of the values of the hashtable. |
Set entrySet() It returns a set view of the mappings contained in the hashtable. |
int hashCode() It returns the hash code of the hashtable. |
Object clone() It returns a shallow copy of the Hashtable. |
V remove(Object key) It returns the value associated with given key and removes the same. |
boolean remove(Object key, Object value) It removes the specified values with the associated specified keys from the hashtable. |
boolean contains(Object value) It returns true if the specified value found within the hash table, else return false. |
boolean containsValue(Object value) It returns true if the specified value found within the hash table, else return false. |
boolean containsKey(Object key) It returns true if the specified key found within the hash table, else return false. |
V replace(K key, V value) It replaces the specified value for a specified key. |
boolean replace(K key, V oldValue, V newValue) It replaces the old value with the new value for a specified key. |
void replaceAll(BiFunction function) It replaces each entry's value with the result of invoking the given function on that entry until all entries have been processed or the function throws an exception. |
void rehash() It is used to increase the size of the hash table and rehashes all of its keys. |
String toString() It returns a string representation of the Hashtable object. |
V merge(K key, V value, BiFunction remappingFunction) If the specified key is not already associated with a value or is associated with null, associates it with the given non-null value. |
void forEach(BiConsumer action) It performs the given action for each entry in the map until all entries have been processed or the action throws an exception. |
boolean isEmpty() It returns true if Hashtable has no elements; otherwise returns false. |
int size() It returns the total number of elements in the Hashtable. |
void clear() It is used to remove all the lements of a Hashtable. |
boolean equals(Object o) It is used to compare the specified Object with the Hashtable. |
The Java Hashtable class provided methods are implemented in the below given examples. Let's go through the examples one by one and understand the uses for each method.
Example 1 : Methods for Adding elements in Hashtable
Output
Hashtable Elements: {700=Python, 400=C, 200=C++, 100=Java}
After calling putIfAbsent(): {700=Python, 500=Go Lang, 400=C, 200=C++, 100=Java}
Hashtable Elements after adding another Hashtable:
{700=Python, 600=MongoDB, 500=Go Lang, 400=C, 300=MySQL, 200=C++, 100=Java}
Example 2 : Methods for Accessing elements from Hashtable
Output
Hashtable Elements: {700=Python, 500=Go Lang, 400=C, 200=C++, 100=Java}
Iterate the map using for-each loop
Key: 700 Value: Python
Key: 500 Value: Go Lang
Key: 400 Value: C
Key: 200 Value: C++
Key: 100 Value: Java
After called map.get(200): C++
Returns a Collection view of the values contained in map
Python
Go Lang
C
C++
Java
Example 3 : Methods for Updating elements in Hashtable
Output
Hashtable Elements: {700=Python, 500=Go Lang, 400=C, 200=C++, 100=Java}
After called map.replace(200, "C#"):
{700=Python, 500=Go Lang, 400=C, 200=C#, 100=Java}
After called map.replace(100, "Java", "JAVA/J2EE"):
{700=Python, 500=Go Lang, 400=C, 200=C#, 100=JAVA/J2EE}
After called map.replaceAll((k,v) -> "MongoDB"):
{700=MongoDB, 500=MongoDB, 400=MongoDB, 200=MongoDB, 100=MongoDB}
Example 4 : Methods for Removing elements from Hashtable
Output
Hashtable Elements: {700=Python, 600=MongoDB, 500=Go Lang, 400=C, 300=MySQL, 200=C++, 100=Java}
After called map.remove(300): {700=Python, 600=MongoDB, 500=Go Lang, 400=C, 200=C++, 100=Java}
Afte called map.remove(700, "Python"):
{600=MongoDB, 500=Go Lang, 400=C, 200=C++, 100=Java}
After called map.remove(900, "HTML"):
{600=MongoDB, 500=Go Lang, 400=C, 200=C++, 100=Java}
After called map.clear(): {}
Example 5 : Utility methods of Hashtable
Output
Hashtable Elements: {700=Python, 500=Go Lang, 400=C, 200=C++, 100=Java}
Hashtable Size: 5
Is Map is Empty: false
map.containsKey(200): true
map.containsValue("Java"): true
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Hashtable.html
That's all guys, hope this Java article is helpful for you.
Happy Learning... 😀
feedback@javabytechie.com
What is the difference between HashMap and Hashtable?
HashMap and Hashtable both implement the Map interface and accept values in the form of key-value pairs. Both the classes look similar, but there are many differences between them. Let's see the below given table.
Comparison Parameters | HashMap Vs Hashtable |
---|---|
Synchronized | HashMap is not synchronized by default, whereas HashTable is by default synchronized. |
Thread Safe | HashMap is not thread safe, whereas HashTable is thread safe. |
Null keys and null values | Hashmap allows one null key and any number of null values, whereas Hashtable does not allow null keys or null values. |
Iterating the values | Hashmap object values are iterated by using an iterator, whereas HashTable is the only class other than vector that uses an enumerator to iterate the values of HashTable objects. |
Fail-fast iterator | The iterator in Hashmap is a fail-fast iterator, while the enumerator for Hashtable is not. If the Hashtable is structurally modified at any time after the iterator is created in any way except the iterator's own remove method, then the iterator will throw a Note: Structural modification means adding or removing elements from the Collection object. Thus, the enumerations returned by the Hashtable keys and elements methods are not fail-fast. |
Performance | Hashmap is much faster and uses less memory than Hashtable as the former is unsynchronized. In a single-threaded environment, unsynchronized objects are often much better in performance when compared to synchronized objects like hashtables. |
Superclass | Hashtable is a subclass of the Dictionary class, which is now obsolete in JDK 1.7, so it is not used anymore. It is better off externally synchronizing a HashMap or using a ConcurrentMap implementation (e.g., ConcurrentHashMap). HashMap is a subclass of the AbstractMap class. Although Hashtable and HashMap have different superclasses, they are both implementations of the "Map" abstract data type. |
Legacy Class | HashMap is not a legacy class, whereas Hashtable is a legacy class in Java. |
Introduced | HashMap was introduced in the JDK 1.2 version, whereas Hashtable was introduced in the JDK 1.0 version. |