Java ProgramsCollectionsHashtable Example

Hashtable Example in Java

beginner·  Collections  ·  Map

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().

Input
put(Apple, 5), put(Banana, 2)
Output
Apple: 5

Java Program

Java
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

Apple: 5

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.

How It Works
  1. 1new Hashtable<String, Integer>() creates a table that stores key-value pairs, the same basic shape as a HashMap.
  2. 2put("Apple", 5) and put("Banana", 2) insert two entries.
  3. 3get("Apple") retrieves the value stored under that key, printed as "Apple: 5".
  4. 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.
After both entries are added, 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.

Complexity
Time Complexity: O(1)Space Complexity: O(n)

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.

Key Concepts

Hashtablesynchronized methodslegacy collection

Related Programs