Sobes.tech
Junior — Middle

What happens to an object inside a HashMap if its key becomes invalid or its identifier changes?

sobes.tech AI

Answer from AI

In Java, if an object used as a key in a HashMap changes its fields that participate in the calculation of hashCode() or equals(), it will cause problems when searching for this key in the map.

HashMap uses hashCode() to determine the bucket, and equals() to find the exact key within the bucket. If the key changes after being placed in the map, then:

  • hashCode() may return a different value, and the object will end up in the wrong bucket.
  • When trying to retrieve a value by key, the search will not find the object because it is "lost" in another bucket.

Therefore, keys in HashMap should be immutable or should not change the fields involved in hashCode() and equals().

Example:

class Key {
    int id;
    public int hashCode() { return id; }
    public boolean equals(Object o) { /* comparison by id */ }
}

Key key = new Key();
key.id = 1;
HashMap<Key, String> map = new HashMap<>();
map.put(key, "value");

key.id = 2; // changing the key

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

Changing the key after adding it to HashMap makes it impossible to find the corresponding value.