In Java, HashMap has specific behavior when it comes to handling null keys and values:
✅ null Key Handling in HashMap
-
A
HashMapallows onenullkey. -
Internally, the
nullkey is treated specially and stored in the first bucket (index 0). -
If you insert another entry with
nullas the key, it will overwrite the previous one.
✅ null Values
-
A
HashMapallows multiple entries withnullvalues.
๐ Example:
import java.util.HashMap;
public class NullKeyExample {
public static void main(String[] args) {
HashMap<String, String> map = new HashMap<>();
map.put(null, "first"); // First null key
map.put("one", "1");
map.put(null, "second"); // Overwrites the previous null key
System.out.println(map.get(null)); // Outputs: second
System.out.println(map); // Outputs: {null=second, one=1}
}
}
⚠️ Notes:
-
If you use other
Mapimplementations (e.g.,TreeMaporHashtable), behavior differs:-
TreeMapthrowsNullPointerExceptionif you usenullas a key (unless a customComparatorsupports it). -
Hashtabledoes not allownullkeys or values.
-
๐ง How HashMap Internally Handles null Key
When you call:
map.put(null, "value");
HashMap internally routes it differently than regular keys.
๐ง Behind the Scenes (Java 8+):
Here's roughly what happens in the put() method of HashMap:
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
๐ hash(key):static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
If the key is
null, it returns a hash of0.
So the null key always hashes to bucket index 0.
๐ Special Handling in putVal():
In putVal():
-
If the key is
null, it directly checks index 0. -
If a node with
nullkey is already present, it updates the value. -
Otherwise, it adds a new
Nodeat index 0.
if (tab[i = (n - 1) & hash] == null)
tab[i] = newNode(hash, key, value, null);
Since hash = 0 for null key, i = 0, so it stores it in bucket 0.
๐ฅ Retrieval with get(null)
Similarly, in get():
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
Again,hash(null)returns0, and it searches bucket 0.
It compares keys using==fornull, avoidingequals()calls.
๐งช Quick Test
map.put(null, "value1");
System.out.println(map.get(null)); // Outputs: value1
map.put(null, "value2");
System.out.println(map.get(null)); // Outputs: value2
Each new put(null, ...) just overwrites the old one at index 0. 
Comments
Post a Comment