Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to demonstrate the use of Hashtable.

Java Code Example — Collection Programs

ADVERTISEMENT

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

  1. Create a Hashtable.
  2. Use put(key, value) to insert Pin Codes (Integers) as keys and City Names as values.
  3. Extract the keys using keySet().
  4. 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

  • Hashtable is 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, HashMap is preferred in modern Java applications unless you strictly require thread safety.

Complexity

Time Complexity O(1) - For basic operations.
Space Complexity O(n)
ADVERTISEMENT