Sobes.tech
Junior — Middle

What happens in HashMap if the key becomes mutable after insertion?

sobes.tech AI

Answer from AI

If the key in a HashMap is modified after insertion, it leads to data structure integrity issues. HashMap uses the hash code of the key to determine its position in the table. If the key is changed such that its hash code or equality (equals) changes:

  • Searching with the modified key will likely fail to find the object, as the hash code points to a different bucket.
  • Internal methods like get(), containsKey(), and others may not work correctly.
  • This can result in the element being 'lost' in the map, even though it physically exists.

Therefore, keys in a HashMap should be immutable or not change after insertion.

Example of the problem:

Map<List<String>, String> map = new HashMap<>();
List<String> key = new ArrayList<>();
key.add("a");
map.put(key, "value");

key.add("b"); // changed the key after insertion

System.out.println(map.get(key)); // most likely null

It is recommended to use immutable objects as keys.

What happens in HashMap if the key becomes mutable… - sobes.tech