Given Hashtable, IdentityHashMap, WeakHashMap, and EnumMap, how do you decide which specialty map fits a problem?
answer
- Enum keys -> EnumMap
- Die-with-key (GC) -> WeakHashMap
- Identity (==) -> IdentityHashMap
- Thread-safe -> ConcurrentHashMap, NOT Hashtable
- Else -> HashMap (Hashtable is legacy)
basics
~20 sPick by the special requirement: EnumMap for enum keys (fast, ordered), WeakHashMap when entries should disappear once keys are unused, IdentityHashMap when keys must match by identity (==), and avoid Hashtable (legacy) — use HashMap or ConcurrentHashMap.
solid answer
~50 sEach specialty map answers a different question. Use EnumMap when keys are constants of one enum type — it's array-indexed by ordinal, likely faster than HashMap and compact when most constants are mapped, with deterministic ordering. Use WeakHashMap when you want entries to be garbage-collectible once their keys are no longer strongly referenced elsewhere — typical for non-owning metadata or caches keyed by such objects. Use IdentityHashMap when key matching must be by object identity (==) rather than equals — for object-graph algorithms like serialization, deep copy, and cycle detection. Avoid Hashtable: it's a Java 1.0 legacy class with one coarse synchronized lock and no null support; for single-threaded use HashMap, for concurrency use ConcurrentHashMap. A quick decision: shared across threads -> ConcurrentHashMap; enum keys -> EnumMap; keys should die with their objects -> WeakHashMap; identity semantics -> IdentityHashMap; otherwise -> HashMap.
go deeper
Can match each map to a one-line use: enum keys -> EnumMap, GC-able keys -> WeakHashMap, identity -> IdentityHashMap, avoid Hashtable.
Explains the deciding requirement behind each choice and why Hashtable is legacy in favor of ConcurrentHashMap/HashMap.
Reasons through tradeoffs (ordinal indexing, weak-key GC semantics and leaks, identity-equality correctness, lock granularity) and selects confidently with caveats.
Sets team conventions, weighs these against alternatives (cache libraries such as Caffeine, soft references, immutable maps), considers API/maintenance impact, and guides migration off legacy Hashtable in large codebases.
## Why specialty maps exist `HashMap` is the default Java map: any key type, logical (`equals`) matching, no thread-safety, arbitrary iteration order. The four specialty maps each exist for **one specific niche**. Choosing well means matching the niche to your actual requirement. ## The decision dimensions Ask these questions, but settle thread-safety first: `EnumMap`, `WeakHashMap` and `IdentityHashMap` are all unsynchronized, so if threads share the map, question 4 comes first, and keeping one of these niches means synchronizing externally, typically on an object that encapsulates the map or through `Collections.synchronizedMap`. ### 1. Are the keys constants of a single enum type? -> EnumMap `EnumMap` is backed by a plain array indexed by each key's `ordinal()` (its position in the enum). No hashing, no collisions, no per-entry node objects — so it's **likely faster** than `HashMap` (the Javadoc says "likely (though not guaranteed)") and compact when most constants are mapped, and it iterates in **enum declaration order** (deterministic). Constraints: keys must all be from the same enum (fixed at construction), inserting a null key throws, null values allowed, not thread-safe. **Rule: single-threaded enum keys -> prefer EnumMap.** ### 2. Should an entry vanish once its key is no longer used elsewhere? -> WeakHashMap `WeakHashMap` holds **keys via weak references**: if nothing else strongly references a key, the garbage collector can reclaim it and the map drops the entry (lazily, via a `ReferenceQueue`, on later map access). This is for **non-owning associations**: attaching metadata to objects you don't control, or caches that must not keep their keys alive. Gotchas: only keys are weak (a value referencing its key pins the entry), removal timing is non-deterministic, string literals and cached boxed values stay reachable, keys with value-based `equals` confuse lookups (the Javadoc aims the class at identity-`equals` keys), not thread-safe. ### 3. Must keys match by *identity* (`==`), not *value* (`equals`)? -> IdentityHashMap Normal maps treat two distinct-but-`equals` objects as one key. `IdentityHashMap` deliberately uses **reference equality (`==`)** and `System.identityHashCode()`, so only the *same instance* is the same key. This is exactly what **object-graph algorithms** need — serialization, deep copy, cycle detection — to track "have I seen *this exact object*?". It's the wrong choice as a general map; keying on value types (String, boxed Integer) causes silent lookup misses. ### 4. Do you need thread-safety? -> ConcurrentHashMap (not Hashtable) `Hashtable` is the Java 1.0 ancestor: thread-safe only via **one lock its map methods share**, so those calls are serialized and it doesn't scale; it also rejects null keys/values and extends the obsolete `Dictionary`. It's **legacy** — don't choose it for new code. For concurrency use `ConcurrentHashMap` (fine-grained locking / lock-free reads, scales across cores). If you must fully-synchronize a `HashMap`, `Collections.synchronizedMap` works but still has one coarse lock. ### 5. None of the above? -> HashMap The default. Any keys, `equals`-based matching, no synchronization overhead, allows one null key and null values, not thread-safe. ## Quick reference table | Requirement | Choose | Key matching | Notable trait | |---|---|---|---| | Keys are one enum type | **EnumMap** | ordinal index | fast, compact, ordered, no null key | | Entries should be GC-eligible | **WeakHashMap** | equals (weak keys) | non-owning metadata/caches | | Identity-based keys | **IdentityHashMap** | `==` / identityHashCode | graph/serialization | | Thread-safe | **ConcurrentHashMap** | equals | scalable; (Hashtable is legacy) | | General default | **HashMap** | equals | allows null key/values | ## Common mistakes - Reaching for `Hashtable` for thread-safety (use `ConcurrentHashMap`). - Using `IdentityHashMap` as a general map and hitting phantom lookup misses. - Expecting `WeakHashMap` entries to disappear deterministically, or forgetting a value->key reference pins them. - Defaulting to `HashMap<EnumType, V>` for single-threaded use when `EnumMap` fits. ## One-line summary Match the map to the *one* special requirement: enum keys -> EnumMap; die-with-key -> WeakHashMap; identity -> IdentityHashMap; thread-safe -> ConcurrentHashMap; else HashMap (and don't pick legacy Hashtable for new code).
- A teammate uses Hashtable 'because it's thread-safe.' What do you advise?Switch to ConcurrentHashMap. Hashtable serializes its map calls through one lock and won't scale; ConcurrentHashMap uses fine-grained locking and lock-free reads. If they only need a synchronized HashMap, Collections.synchronizedMap exists, but it has the same single-lock limitation as Hashtable.
- You need to cache computed results keyed by domain objects, but the cache must not cause memory leaks. Which map and what caveat?WeakHashMap, so entries become collectible when the keys are no longer used elsewhere. Caveat: only keys are weak, so if a cached value references its key it pins the entry (leak); a domain object with value-based equals can lose its entry while an equal key still exists; and timing of removal is non-deterministic. For value-driven eviction, a real cache library is often better.
Choosing a specialty map is like choosing a tool by the one job it's shaped for: a torque wrench (EnumMap, precise+fast for a fixed set), disappearing ink (WeakHashMap, fades when unused), fingerprint lock (IdentityHashMap, identity not name), and an old single-key padlock everyone shares (Hashtable, replaced by the modern multi-lock ConcurrentHashMap).
- Recommending Hashtable for new concurrent code.
- Using IdentityHashMap or WeakHashMap as a general-purpose default map.
- Never considering EnumMap for single-threaded enum keys.
- Assuming EnumMap, WeakHashMap or IdentityHashMap is thread-safe without a wrapper.
- Hashtable
- Java 1.0
- IdentityHashMap
- Java 1.4
- WeakHashMap
- Java 1.2
- EnumMap
- Java 1.5
- ConcurrentHashMap
- Java 1.5
context
- Hashtable (Java SE 27 & JDK 27)docs.oracle.com
- WeakHashMap (Java SE 27 & JDK 27)docs.oracle.com
- EnumMap (Java SE 27 & JDK 27)docs.oracle.com