Junior — Middle
What is the maximum possible number of null-valued elements in a HashMap?
sobes.tech AI
Answer from AI
In Java, HashMap allows exactly one element with a null key. This is because HashMap specifically handles the null key by placing it in a separate bucket without computing a hash code.
As for values, HashMap does not limit the number of elements with a null value. That is, you can have as many key-value pairs where the value is null.
Example:
HashMap<String, String> map = new HashMap<>();
map.put(null, "value"); // one null key is allowed
map.put("key1", null); // null value is allowed
map.put("key2", null); // multiple null values are also allowed