Junior — Middle
Is it allowed to store null as a key in HashMap?
sobes.tech AI
Answer from AI
In Java, HashMap allows storing null as a key. Specifically, HashMap permits exactly one null key.
This is possible due to implementation details: for the null key, a separate logic is used that does not call hashCode(), but stores the value in a special place.
Example:
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
Unlike HashMap, some other implementations, such as Hashtable, do not allow null as a key.