Hashtable
Hashtable¶
Think of Hashtable as an old vault with strict guards π
Everything is locked down, thread-safe by default⦠but a bit slow and outdated compared to modern options.
π§ What is Hashtable?¶
Hashtable is part of the Java Collections Framework
π It stores key β value pairs (like HashMap)
π But with built-in synchronization
π Key Characteristics¶
- β Thread-safe (synchronized)
- β No null key
- β No null value
- β Keys are unique
- β No order guarantee
- Slower than
HashMapdue to synchronization
ποΈ Internal Working¶
- Uses hashing (bucket array)
- Key β
hashCode()β bucket index - Handles collisions using chaining
π Every method is synchronized, so only one thread can access at a time
βοΈ Important Methods¶
Hashtable<String, Integer> table = new Hashtable<>();
table.put("A", 1);
table.put("B", 2);
table.get("A");
table.remove("B");
table.containsKey("A");
table.containsValue(1);
table.size();
π§ Example¶
Hashtable<String, Integer> table = new Hashtable<>();
table.put("Java", 1);
table.put("Python", 2);
// table.put(null, 3); // β throws NullPointerException
System.out.println(table);
π Output (order not guaranteed):
βοΈ Hashtable vs HashMap¶
| Feature | Hashtable π§° | HashMap β‘ |
|---|---|---|
| Thread-safe | β Yes | β No |
| Performance | Slower | Faster |
| Null key | β No | β Yes |
| Null value | β No | β Yes |
| Legacy | β Yes | β No |
π― Interview Nuggets¶
Hashtableis legacy class (introduced in Java 1.0)-
Replaced in most cases by:
HashMap(non-thread-safe)ConcurrentHashMap(thread-safe & efficient)- Synchronization is at method level β causes bottleneck
π§ Memory Trick¶
Hashtable = Thread-safe but heavy (old-school lock system π)