Middle+
You are performing a get by key in a HashMap, but the element is not found, even though you are sure that this pair was inserted. How can this happen?
sobes.tech AI
Answer from AI
This can happen if the hashCode() and equals() methods are overridden in the keys, but done incorrectly. For example, if hashCode() returns different values for the same object across different calls, or equals() does not adhere to the contract, then HashMap will not be able to find the element.
Other reasons:
- The key was modified after insertion (mutable object used as a key).
- A different object with the same data is used, but without proper overriding of
equalsandhashCode.
Example of an incorrect key:
class Key {
int id;
@Override
public int hashCode() {
return new Random().nextInt(); // Incorrect!
}
@Override
public boolean equals(Object o) {
// ...
}
}
Because of this, key lookup will not work.