Java Program to demonstrate the use of Hashtable.
Objective
Write a Java program to store Key-Value pairs using the legacy Hashtable class.
Algorithm / Approach
- Create a
Hashtable. - Use
put(key, value)to insert Pin Codes (Integers) as keys and City Names as values. - Extract the keys using
keySet(). - Iterate through the keys and use
get(key)to retrieve and print the associated Cities.
Test.java
import java.util.*;
class Test {
public static void main(String[] a)
{
Hashtable city = new Hashtable();
city.put(110002,"Delhi");
city.put(201301,"Noida");
city.put(208001,"Kanpur");
city.put(221173,"Varanasi");
System.out.println(city);
System.out.println("Traversing...");
Set keys = city.keySet();
Iterator i = keys.iterator();
while(i.hasNext()) {
int x =(int) i.next();
System.out.print(x+"- ");
System.out.println(city.get(x));
}
}
}
Expected Output
{221173=Varanasi, 208001=Kanpur, 110002=Delhi, 201301=Noida}
Traversing...
221173- Varanasi
208001- Kanpur
110002- Delhi
201301- Noida
Explanation of the Program
Hashtableis a legacy class from Java 1.0 that implements a key-value hash map.- It functions almost exactly identically to the modern
HashMap, with one major difference: Hashtable is entirely synchronized (thread-safe). - Because synchronization adds significant performance overhead,
HashMapis preferred in modern Java applications unless you strictly require thread safety.
Complexity
Time Complexity
O(1) - For basic operations.
Space Complexity
O(n)