In Java, HashMap
has specific behavior when it comes to handling null
keys and values:
✅ null
Key Handling in HashMap
-
A
HashMap
allows onenull
key. -
Internally, the
null
key is treated specially and stored in the first bucket (index 0). -
If you insert another entry with
null
as the key, it will overwrite the previous one.
✅ null
Values
-
A
HashMap
allows multiple entries withnull
values.
๐ 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
Map
implementations (e.g.,TreeMap
orHashtable
), behavior differs:-
TreeMap
throwsNullPointerException
if you usenull
as a key (unless a customComparator
supports it). -
Hashtable
does not allownull
keys 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
null
key is already present, it updates the value. -
Otherwise, it adds a new
Node
at 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