Sobes.tech
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, the null key is handled separately, without computing a hash code (since null does not have one).
  • When searching or inserting with a null key, a separate logic is used that specifically checks for null.

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.