Skip to content

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

Hashtable<String, Integer> table = new Hashtable<>();

πŸ‘‰ 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 HashMap due to synchronization

πŸ—οΈ Internal Working

Image

Image

Image

Image

Image

  • 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):

{Java=1, Python=2}

βš”οΈ 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

  • Hashtable is 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 πŸ”)