HashCode mixes in a field that equals ignores, so equal objects can hash differently

tx0/java:hash-field-not-in-equalsrecommendedwarningbug

What it finds

Objects that are equal must have the same hash code, as the contract of Object.hashCode says. When hashCode mixes in a field that equals ignores, two objects that differ only in that field are equal but hash differently, so a HashMap or HashSet fails to find one by the other.

Reported is a field of the class that hashCode() reads but that equals(Object) does not mention at all, not even through a getter named after it. A class whose equals calls super.equals or another method of its own object, other than getters, is left alone, since that may compare more, and so is a field that hashCode assigns or that is named for a hash, which caches the hash.

From the rule's source, hash_field_not_in_equals.rs.

Example from the rule's tests
import java.util.Objects; class Point {  int x;  int y;  String name;  private int hash;   @Override  public boolean equals(Object o) {    Point p = (Point) o;    return x == p.x && getName().equals(p.getName());  }   @Override  public int hashCode() {    int h = hash;    if (h == 0) {      h = Objects.hash(x, y, name);tx0 reports: hashCode reads y, which equals does not compare      hash = h;    }    return h;  }   String getName() {    return name;  }}
Highlighted lines are the ones tx0 reports, with its message under each; the other lines are left alone.

Turn it on, off or suppress it

The rule runs from the recommended tier up. To turn it on in a lower tier, give it a level in tx0.toml:

tx0.toml
[rules]
"tx0/java:hash-field-not-in-equals" = "warning"

To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:

// tx0: ignore[tx0/java:hash-field-not-in-equals] reason="..."

tx0 explain tx0/java:hash-field-not-in-equals shows the same in the terminal. Found a false positive? Report it.