Junior — Middle
What happens if you insert a record with a null key into a HashMap?
sobes.tech AI
Answer from AI
In Java, HashMap allows the use of null as a key. If you insert an entry with a null key, it will be placed in a special slot designated for the null key.
Features:
- Inside
HashMap, thenullkey is handled separately, without computing a hash code (sincenulldoes not have one). - When searching or inserting with a
nullkey, a separate logic is used that specifically checks fornull.
Example:
HashMap<String, Integer> map = new HashMap<>();
map.put(null, 42);
System.out.println(map.get(null)); // Will output 42
Thus, HashMap can have exactly one null key. If you try to add a second entry with a null key, the value will be overwritten.