Junior — Middle
How does changing the key affect the structure and behavior of HashMap in Java?
sobes.tech AI
Answer from AI
In a HashMap, keys are used to compute the hash code and determine the position of the element in the internal structure (bucket). If the object used as a key is changed such that its hash code or the result of the equals() method changes, it will break the HashMap.
Why?
- When an element is added, the key is hashed, and the element is placed in a specific bucket.
- When searching for an element by key, the
HashMapcomputes the hash and looks in the corresponding bucket.
If the key changes after being added, then searching with the new key state will compute a different hash, and the element will not be found — it will be "lost" in the map.
Therefore, keys in a HashMap should be immutable or not change while they are used as keys.
Example of the problem:
class Key {
int id;
Key(int id) { this.id = id; }
public int hashCode() { return id; }
public boolean equals(Object o) { return o instanceof Key && ((Key)o).id == id; }
}
Key key = new Key(1);
HashMap<Key, String> map = new HashMap<>();
map.put(key, "value");
key.id = 2; // changed the key
System.out.println(map.get(key)); // null, because the key "lost" itself