Junior — Middle
Is it allowed to use null as a key in a hash table HashMap?
sobes.tech AI
Answer from AI
In Java, the HashMap class allows the use of null as a key. Specifically, HashMap permits one null key and multiple null values. This is because HashMap is implemented based on an array of buckets and linked lists, and separate handling is provided for the null key.
Example:
HashMap<String, Integer> map = new HashMap<>();
map.put(null, 123);
System.out.println(map.get(null)); // Will output 123
However, in other Map implementations, such as TreeMap, null keys are not allowed because key comparison is used.