Question 24 · Section 10

Can HashMap Store a null Key?

On put(null, value):

Language versions: English Russian Ukrainian

🟢 Junior Level

Yes, HashMap allows using one null as a key. If you try to add a second null key, the value is simply overwritten.

Example:

HashMap<Object, String> map = new HashMap<>();
map.put(null, "First");
map.put(null, "Second"); // Overwrites

System.out.println(map.get(null)); // "Second"
System.out.println(map.size());    // 1 (only one null key)

How it works: HashMap handles null specially — for it, hash(null) = 0, and it always lands in the first bucket (table[0]).

Other Maps:

  • ConcurrentHashMapno (throws NullPointerException)
  • TreeMapno (keys need to be compared)
  • Hashtableno (old implementation)

🟡 Middle Level

Technical Implementation

static final int hash(Object key) {
    int h;
    return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}

On put(null, value):

  1. hash(null) returns 0
  2. index = (n - 1) & 0 = 0
  3. Element is placed in table[0]

Comparison of Implementations

Implementation Null key Null values
HashMap Yes (1) Yes (many)
LinkedHashMap Yes (1) Yes
TreeMap No Yes
ConcurrentHashMap No No
Hashtable No No

Why is This Dangerous?

  1. Non-obviousness — a null key can be a bug that’s hard to detect
  2. Implicit null key can cause NPE in code that doesn’t expect null among keys (e.g., key.length() without a null check)
  3. Incompatibility — switching to ConcurrentHashMap will break the code

Best Practices

  • Avoid using null as a key
  • Use the Null Object pattern or a constant:
    static final Object EMPTY_KEY = new Object();
    map.put(EMPTY_KEY, defaultValue);
    

Common Mistakes

  1. Accidental null — a method result returned null, and you put it as a key
  2. Iteration without check — NPE when using the key

🔴 Senior Level

Internal Mechanics

Null key is handled separately in putVal:

if (key == null)
    hash = 0;
else
    hash = spread(key.hashCode());

On collisions in bucket 0:

// Comparison: (p.key == key || (key != null && key.equals(p.key)))
// For null: p.key == null → true (reference comparison)

Null is compared only via ==equals() is not called.

Security Implications

Null key as an attack vector:

  • On JSON/XML deserialization, a null key can come from an invalid input document. Handle this explicitly to avoid NPE in code that doesn’t expect null among keys.

Why ConcurrentHashMap Forbids Null?

Ambiguity in multi-threading:

// In ConcurrentHashMap:
// get(key) = null unambiguously = key is absent
// No second containsKey() call needed

In HashMap with null keys:

V val = map.get(key);
if (val == null) {
    // No key? Or value = null?
    if (!map.containsKey(key)) {
        // TOCTOU race in multi-threading!
    }
}

Alternative Patterns

Null Object Pattern:

enum SpecialKey { NONE }
map.put(SpecialKey.NONE, defaultValue);

Optional:

Map<Optional<String>, Value> map; // But this is overkill

Production Diagnostics

When debugging null keys:

  • Null key is invisible in some profilers
  • Heap dump shows Entry with key = null
  • In logs: null=SomeValue — may look like a formatting bug

🎯 Interview Cheat Sheet

Must know:

  • HashMap allows ONE null key, hash(null) = 0 → table[0]
  • On repeated put(null, …), value is overwritten
  • null is compared via ==, equals() is not called
  • ConcurrentHashMap/TreeMap/Hashtable forbid null keys (NPE)
  • On JSON/XML deserialization, a null key can come from an invalid document
  • Null Object Pattern: use a constant EMPTY_KEY instead of null

Common follow-up questions:

  • Why does ConcurrentHashMap forbid null keys? — ambiguity: get=null = no key or value=null?
  • How many null keys are allowed? — exactly one, a second overwrites
  • Why is a null key dangerous? — NPE in code that doesn’t expect null among keys
  • How to protect? — Null Object Pattern, Optional, or explicit input validation

Red flags (DO NOT say):

  • “HashMap doesn’t allow null keys” — it does, one
  • “null key = a bug” — it’s allowed behavior, though not recommended
  • “ConcurrentHashMap allows null keys” — no, it throws NPE

Related topics:

  • [[25. Can HashMap Store a null Value]]
  • [[14. What Are the Requirements for a HashMap Key]]
  • [[23. What is ConcurrentHashMap and How Does It Differ from HashMap]]