Sobes.tech
Senior

Question 3. What can go wrong if the key object field used for calculating hashCode is changed after insertion into HashMap? - Searching by key will return the wrong object - Searching by key will slow down - Searching by key will not return the object

sobes.tech AI

Answer from AI

If a field of an object used to compute hashCode changes after inserting the object into a HashMap, then searching for this key will not return the object. This happens because HashMap uses hashCode to determine the bucket where the object is stored. When the hashCode field changes, the object will be searched in a different bucket where it does not exist.

Therefore, the correct answer is:

  • Searching by key will not return the object

Example:

class Key {
    int id;
    
    Key(int id) { this.id = id; }

    @Override
    public int hashCode() {
        return id;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Key)) return false;
        return id == ((Key) o).id;
    }
}

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

// Changing the field that affects hashCode
key.id = 2;

// Search by key will not work
System.out.println(map.get(key)); // null

This is one of the reasons why objects used as keys in HashMap should be immutable.