DEV Community

Ramya K
Ramya K

Posted on

Why Java hashmap uses null key and stores it in 0th index?

In Java's HashMap, a null key is stored in bucket 0 because the hashCode() method cannot be invoked on a null reference.
When a key-value pair is added to a HashMap, the hashCode() method of the key is typically used to determine the bucket index where the entry will be stored. However, if the key is null, calling null.hashCode() would result in a NullPointerException.
To handle null keys gracefully, HashMap explicitly checks if the key is null. If it is, the HashMap implementation assigns it to a default, fixed location, which is conventionally bucket 0. This allows HashMap to support null keys without encountering runtime errors, and ensures that null keys are consistently placed in a predictable location.
This design choice allows null to serve as a valid key, potentially useful for representing default values or special cases within the map. It is important to note that only one null key can exist in a HashMap at any given time, as keys must be unique.

Top comments (0)