Junior — Middle
What happens if you insert a record with null as the key into a HashMap?
sobes.tech AI
Answer from AI
In Java, HashMap allows using null as a key. When inserting a record with a null key, the element is placed in a special bucket because the hashCode() method cannot be called on null. Thus, HashMap stores one record with a null key. If multiple records with a null key are inserted, the last one overwrites the previous ones.
Example:
HashMap<String, String> map = new HashMap<>();
map.put(null, "value1");
map.put(null, "value2");
System.out.println(map.get(null)); // Will output "value2"
If Hashtable is used, inserting null as a key will throw a NullPointerException, because Hashtable does not support null keys.