Video in progress

Strong Junior 🧺 Collections

What happens if an object used as a HashMap key is modified afterwards?

The object stays in the bucket chosen by its old hash, while the new hash points somewhere else. So get and containsKey can't find it, but the entry stays in the map as if "lost".

📖 Answer

class Tag {
    String name;
    Tag(String n) { name = n; }
    @Override public boolean equals(Object o) { return o instanceof Tag t && t.name.equals(name); }
    @Override public int hashCode() { return name.hashCode(); }
}

Set<Tag> tags = new HashSet<>();
Tag t = new Tag("java");
tags.add(t);
t.name = "kotlin";

tags.contains(t);               // false
tags.contains(new Tag("java")); // false too: the hash matches, equals doesn't
tags.size();                    // 1

The element can't be found anywhere, and you can't remove it either. This is a kind of memory leak: the map keeps growing, but you can't reach what is inside it.

The rule: use only immutable objects as keys: String, Long, UUID, a record (if its fields are immutable too). The same problem shows up when you put JPA entities into a HashSet: the id is null before saving and gets a value afterwards, and if hashCode depends on id, the element "disappears".