Sobes.tech
Middle

What happens if you try to add a key-value pair to a HashMap where the value is null, and such a pair already exists with a fixed hashCode and equals returning true?

sobes.tech AI

Answer from AI

If a HashMap already contains a pair with a key for which hashCode is fixed and equals returns true, then adding a new pair with the same key and a null value will replace the old value with null. That is, the value associated with this key will be updated to null.

Example:

Map<Key, String> map = new HashMap<>();
Key key = new Key(); // hashCode and equals are implemented so that they are always the same
map.put(key, "value");
map.put(key, null); // replaces "value" with null
System.out.println(map.get(key)); // prints null

Thus, HashMap does not prohibit storing null as a value, and re-adding with the same key updates the value.

What happens if you try to add a key-value pair to a… - sobes.tech