Hashtable in Java is a legacy class that implements the Map interface and extends Dictionary. It is synchronized and stores key-value pairs in a hash table, where keys and values are not ordered. Hashtable does not allow null keys or values and provides thread-safe operations for basic map operations. Here’s an overview of the syntax, methods, and an example demonstrating the use of Hashtable.
import java.util.Hashtable;
// Syntax for creating a Hashtable
Hashtable<KeyType, ValueType> hashtableName = new Hashtable<>();
Code language:JavaScript(javascript)
Constructors
Constructor
Description
Hashtable()
Creates an empty hashtable.
Hashtable(int initialCapacity)
Creates a hashtable with the specified initial capacity.
Hashtable(int initialCapacity, float loadFactor)
Creates a hashtable with capacity and load factor.
Hashtable(Map<? extends K, ? extends V> t)
Copies all mappings from the specified map.
🔹 Common Methods in HashTable
Basic Operations
Method
Description
V put(K key, V value)
Inserts a key-value pair into the table.
V get(Object key)
Returns the value associated with the key.
V remove(Object key)
Removes the key and returns the associated value.
boolean containsKey(Object key)
Returns true if the key exists.
boolean containsValue(Object value)
Returns true if the value exists.
boolean isEmpty()
Checks if the hashtable is empty.
int size()
Returns the number of key-value pairs.
void clear()
Removes all key-value pairs.
Query & View Methods
Method
Description
Enumeration<K> keys()
Returns an enumeration of the keys.
Enumeration<V> elements()
Returns an enumeration of the values.
Set<K> keySet()
Returns a set view of the keys.
Set<Map.Entry<K,V>> entrySet()
Returns a set view of key-value mappings.
Collection<V> values()
Returns a collection view of the values.
Advanced Methods
Method
Description
V compute(K key, BiFunction<? super K,? super V,? extends V> remappingFunction)
Recomputes a value for the key.
V computeIfAbsent(K key, Function<? super K,? extends V> mappingFunction)
Computes value if key is absent.
V computeIfPresent(K key, BiFunction<? super K,? super V,? extends V> remappingFunction)
Computes value if key is present.
V merge(K key, V value, BiFunction<? super V,? super V,? extends V> remappingFunction)
Merges the value with existing one.
void forEach(BiConsumer<? super K, ? super V> action)
Performs the given action for each entry.
void replaceAll(BiFunction<? super K,? super V,? extends V> function)
Replaces each entry’s value using a function.
import java.util.Hashtable;
import java.util.Enumeration;
public class HashtableExample {
public static void main(String[] args) {
// Creating a Hashtable to store student names and their roll numbers
Hashtable<String, Integer> studentTable = new Hashtable<>();
// Adding students to the Hashtable
studentTable.put("Paani", 101);
studentTable.put("Mahesh", 102);
studentTable.put("Datta", 103);
studentTable.put("Ganesh", 104);
studentTable.put("Harsha", 105);
// Displaying the Hashtable
System.out.println("Hashtable of students:");
System.out.println(studentTable);
// Removing a student from the Hashtable
Integer removedRollNumber = studentTable.remove("Datta");
System.out.println("\nRemoved student 'Datta' with roll number: " + removedRollNumber);
// Displaying the updated Hashtable
System.out.println("\nUpdated Hashtable of students:");
System.out.println(studentTable);
// Checking if a student exists in the Hashtable
String searchStudent = "Harsha";
boolean containsStudent = studentTable.containsKey(searchStudent);
System.out.println("\nDoes the Hashtable contain student '" + searchStudent + "'? " + containsStudent);
// Iterating over the entries of the Hashtable using enumeration
System.out.println("\nIterating over Hashtable entries using enumeration:");
Enumeration<String> keys = studentTable.keys();
while (keys.hasMoreElements()) {
String student = keys.nextElement();
System.out.println("Student: " + student + ", Roll Number: " + studentTable.get(student));
}
// Size of the Hashtable
System.out.println("\nSize of the Hashtable: " + studentTable.size());
// Clearing the Hashtable
studentTable.clear();
System.out.println("\nIs the Hashtable empty now? " + studentTable.isEmpty());
}
}
D:\>javac HashtableExample.java
D:\>java HashtableExample
Hashtable of students:
{Ganesh=104, Paani=101, Mahesh=102, Harsha=105, Datta=103}
Removed student 'Datta'with roll number: 103
Updated Hashtable of students:
{Ganesh=104, Paani=101, Mahesh=102, Harsha=105}
Does the Hashtable contain student 'Harsha'? true
Iterating over Hashtable entries using enumeration:
Student: Ganesh, Roll Number: 104Student: Paani, Roll Number: 101Student: Mahesh, Roll Number: 102Student: Harsha, Roll Number: 105
Size of the Hashtable: 4
Is the Hashtable empty now? trueCode language:JavaScript(javascript)
Hashtable in Java is a synchronized data structure that provides thread-safe operations for storing and retrieving key-value pairs. It is suitable for applications requiring synchronization but may have performance implications due to its synchronized nature. Understanding how to use Hashtable effectively allows developers to design robust and concurrent Java applications while ensuring data integrity and consistency.