Hashtable Example in Java
Problem
Hashtable is one of Java's original collection classes, predating the modern Collections framework — it stores key-value pairs like HashMap, but every method is synchronized for thread safety.
Add entries to a Hashtable and read one back with put() and get().
Java Program
import java.util.Hashtable;
public class HashtableExample {
public static void main(String[] args) {
Hashtable<String, Integer> scores = new Hashtable<>();
scores.put("Apple", 5);
scores.put("Banana", 2);
System.out.println("Apple: " + scores.get("Apple"));
}
}Output
Core Logic
Hashtable's put() and get() work just like HashMap's, storing and retrieving values by key — the real difference is internal, not in how it's used here.
- 1
new Hashtable<String, Integer>()creates a table that stores key-value pairs, the same basic shape as a HashMap. - 2
put("Apple", 5)andput("Banana", 2)insert two entries. - 3
get("Apple")retrieves the value stored under that key, printed as"Apple: 5". - 4Every one of Hashtable's methods is internally synchronized, making it safe to share across multiple threads without extra locking — at the cost of that locking overhead on every call, even in single-threaded code that never needed it.
get("Apple") returns 5, printed as "Apple: 5".Key Point: Hashtable also doesn't allow null keys or null values at all — HashMap permits one null key and any number of null values — which is one more reason modern code reaches for HashMap (single-threaded) or ConcurrentHashMap (genuinely concurrent) instead.
Why: put() and get() cost O(1) on average, the same underlying hashing as HashMap — the synchronization adds locking overhead per call, not a different asymptotic cost.