Sobes.tech
Senior

class User { String name; public int hashCode() { return name.hashCode(); } public boolean equals(Object o) { return o instanceof User u && name.equals(u.name); } } Map<User, String> map = new HashMap<>(); User u = new User(); u.name = "Bob"; map.put(u, "developer"); u.name = "Alice"; System.out.println(map.get(u));

sobes.tech AI

Answer from AI

In this example, the name field of the User object changes after it has been used as a key in a HashMap.

HashMap uses the hash code of the key to determine where to store the value. When map.put(u, "developer") is called, u.hashCode() is invoked, which depends on name ("Bob"). After changing u.name = "Alice", the object's hash code changes, but the object remains in the same position in the table.

When calling map.get(u), a new hash code (for "Alice") is computed, which does not match the original, and the search will not find the element. As a result, null will be returned.

Conclusion: You should not modify the fields of an object that participate in the calculation of hashCode and equals if it is used as a key in a HashMap.


Demonstration example:

User u = new User();
u.name = "Bob";

Map<User, String> map = new HashMap<>();
map.put(u, "developer");

u.name = "Alice";

System.out.println(map.get(u)); // null

To avoid such problems, fields involved in hashCode and equals should be immutable, or the object should be immutable.