Differences between a HashMap and a Hashtable in Java?

Here are the key differences between HashMap and Hashtable in Java:

1. Thread Safety & Synchronization

  • Hashtable:
    • Synchronized (thread-safe). Every method is synchronized, which ensures thread safety but introduces performance overhead.
  • HashMap:
    • Not synchronized (not thread-safe by default). Requires explicit synchronization (e.g., Collections.synchronizedMap) for multi-threaded environments.
    • Better performance in single-threaded scenarios due to lack of synchronization.

2. Null Keys/Values

  • Hashtable:
    • Does NOT allow null keys or values. Throws NullPointerException if used.
  • HashMap:
    • Allows one null key and multiple null values.

3. Inheritance & Legacy Status

  • Hashtable:
    • Legacy class (since Java 1.0) extending the Dictionary class (now considered obsolete).
  • HashMap:
    • Part of the modern Java Collections Framework (since Java 1.2) and implements the Map interface.

4. Iteration

  • Hashtable:
    • Uses Enumeration to iterate over keys/values.
  • HashMap:
    • Uses Iterator, which is fail-fast (throws ConcurrentModificationException if modified during iteration).

5. Performance

  • Hashtable:
    • Slower due to synchronization overhead.
  • HashMap:
    • Faster in single-threaded environments. For multi-threaded use, prefer ConcurrentHashMap over synchronized HashMap.

6. Recommended Usage

  • Hashtable:
    • Rarely used today. Largely replaced by ConcurrentHashMap or synchronized wrappers of HashMap.
  • HashMap:
    • Default choice for most scenarios. Use ConcurrentHashMap for thread-safe requirements.

Example:

java

// Hashtable (no nulls allowed)
Hashtable<String, Integer> table = new Hashtable<>();
table.put("key", 100); // OK
table.put(null, 100);  // Throws NullPointerException

// HashMap (allows null)
HashMap<String, Integer> map = new HashMap<>();
map.put("key", 100); // OK
map.put(null, 200);  // OK

Summary

FeatureHashtableHashMap
Thread SafetyYes (synchronized)No (requires external)
Null Keys/ValuesDisallowedAllowed
LegacyYes (Java 1.0)No (Java 1.2+)
PerformanceSlowerFaster
IterationEnumerationIterator (fail-fast)

Prefer HashMap unless legacy code requires Hashtable, and use ConcurrentHashMap for concurrent needs.

Leave a Reply

Your email address will not be published. Required fields are marked *