What are the potential issues with using mutable objects as keys in a HashMap?

Using mutable objects as keys in a HashMap is generally considered a bad practice because changes to the object's state can affect its hashCode() and equals() values after the key has been stored in the map.

Key Points: • HashMap uses hashCode() to determine the bucket where a key-value pair is stored. • If a key's state changes and its hashCode() changes, HashMap may not be able to locate the entry later. • This can result in failed lookups, duplicate logical keys, and difficult-to-diagnose bugs. • Immutable objects such as String, Integer, or custom immutable classes are preferred as HashMap keys.

Example: Suppose an Employee object uses employeeId in its hashCode() and equals() methods. If employeeId is modified after the object is inserted into a HashMap, retrieving the value using the same object may fail because HashMap will search in a different bucket.

Code Example:

import java.util.HashMap;
import java.util.Map;

class Employee {
    int id;

    Employee(int id) {
        this.id = id;
    }

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

    @Override
    public boolean equals(Object obj) {
        Employee e = (Employee) obj;
        return this.id == e.id;
    }
}

public class Test {
    public static void main(String[] args) {

        Map<Employee, String> map = new HashMap<>();

        Employee emp = new Employee(101);
        map.put(emp, "John");

        emp.id = 102; // Mutating key

System.out.println(map.get(emp)); // May return null

    }
}

Interview Tip: A concise interview answer is: Mutable objects should generally not be used as HashMap keys because changing their state after insertion can alter their hashCode() or equals() behavior. This makes the entry difficult or impossible to retrieve. Using immutable objects as keys ensures consistent hashing and reliable map operations.