Advertisement
Advanced Java, equals(), hashCode() & toString() Contracts

How would you implement equals()/hashCode() correctly for a class containing a mutable field, and why does using such a class as a HashMap key or HashSet element create a serious risk?

Short answer

If a field used in equals()/hashCode() computation is mutated after the object has already been inserted into a hash-based collection, the object's hash code effectively "changes" from the collection's perspective, but the collection has no way of knowing this happened and…

Save Java mock interview
Advertisement
AModel answer
If a field used in equals()/hashCode() computation is mutated after the object has already been inserted into a hash-based collection, the object's hash code effectively "changes" from the collection's perspective, but the collection has no way of knowing this happened and doesn't automatically relocate the object to its now-correct bucket -- the practical consequence is that map.get(key)/set.contains(element) can subsequently fail to find an object that IS still logically present in the collection, since the lookup now computes a different bucket location than where the (now-stale-hashed) object actually resides; the strong recommendation is to use only immutable fields (or entirely immutable classes) for equals()/hashCode(), and if a mutable object genuinely must be used as a key, the calling code bears full responsibility for never mutating those specific fields while the object remains in any hash-based collection.
public class MutablePoint {
    private int x, y;  // mutable! setters allow changing after construction
    public void setX(int x) { this.x = x; }

    @Override
    public int hashCode() { return Objects.hash(x, y); }
    // equals() omitted for brevity, also compares x, y
}

Set<MutablePoint> set = new HashSet<>();
MutablePoint p = new MutablePoint();  // x=0, y=0
set.add(p);
p.setX(99);  // mutated AFTER insertion -- hash code effectively changed, but set doesn't know!
System.out.println(set.contains(p));  // often false! Lookup now targets a DIFFERENT bucket than where p actually sits
Real-world example
A caching system using a mutable Configuration object as a HashMap key experiences confusing, intermittent "missing" cache entries whenever the configuration is updated in place after being cached, traced to the mutation silently invalidating the object's effective hash-bucket location, resolved by switching to an immutable configuration key or a stable, separately-generated identifier for the map key instead.
Likely follow-ups
  • What defensive coding practices help prevent accidentally using mutable objects as hash-based collection keys?
  • How does this specific risk relate to the broader design principle favoring immutability for value-like classes?
Related topics