Null Key and Value Restrictions
What you'll learn: Why Hashtable refuses null keys and values while HashMap accepts them.
The Strict No-Null Policy
Hashtable throws a NullPointerException if you try to store a null key or a null value. This design decision stems from its thread-safe implementation and historical origins. In contrast, HashMap is more permissive: it allows one null key (stored in a special position) and any number of null values.
Why the Difference?
Think of Hashtable as an old-school librarian who enforces strict rules: "No book without a label, no label without text!" This strictness made synchronization logic simpler in the original implementation. Since Hashtable must compute hash codes for keys, and calling hashCode() on null would crash the program, the designers simply banned nulls entirely.
HashMap, designed later without built-in synchronization, chose flexibility. It special-cases null keys by placing them in bucket zero (since you can't call hashCode() on null). Null values are simply stored like any other value.
Practical Implications
Hashtable<String, String> legacy = new Hashtable<>();
// legacy.put(null, "value"); // NullPointerException!
// legacy.put("key", null); // NullPointerException!
HashMap<String, String> modern = new HashMap<>();
modern.put(null, "value"); // Works fine
modern.put("key", null); // Also fine
If your code needs to store nulls, HashMap is your only choice between these two. If you're working with legacy Hashtable code, you must ensure no nulls enter the system or wrap them in some placeholder value.
Key Takeaway: Hashtable rejects both null keys and values entirely, while HashMap permits one null key and unlimited null values—choose HashMap when null handling matters.