Skip to content
Junior–Middle718 views

Is it possible to use null as a key in a HashMap in Java?

Practice

AI answer

In Java, the HashMap class allows using null as a key. Specifically, HashMap permits exactly one key with the value null.

This is possible because when computing the hash code for a null key, a special handling is used — instead of calling hashCode(), it returns 0.

Example:

import java.util.HashMap;

public class Example {
    public static void main(String[] args) {
        HashMap<String, String> map = new HashMap<>();
        map.put(null, "value for null key");
        System.out.println(map.get(null)); // Will output: value for null key
    }
}

However, it is important to remember that other Map implementations, such as Hashtable, do not allow null as a key or value.