You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Check that equals() and hashCode() read the same fields #35
If I add a new field to a class, I can remember to update equals() but forget to update hashCode(). How would we detect this? In many cases, both methods should read all fields of a class, but that's probably too strong a check. (For example, a List.equals() implementation might read no fields directly, preferring to operation on the public size() and get() methods.) A weaker but probably still useful check is that the two methods read the same set of fields. False positives are still possible. For example, the check would flag a field containing a cached hash code, which would likely be read in hashCode() but not equals(). This particular example is avoidable by requiring the hashCode() looks at a subset of the fields that equals() looks at. I conjecture that it's more common for programmers to update equals() but forget to update hashCode() than vice versa, so this further weakened check would likely still catch most problems.
This sounds worthwhile. Checking both methods in a class wouldn't be difficult. We may need to exempt classes that only implement one, unless #157 is implemented.
Activity
cushon commentedon Oct 31, 2014
Original comment posted by eaftan@google.com on 2013-02-11 at 08:16 PM
This will require us to do some interprocedural analysis, but it would be a good check.
Status: Accepted
Labels: -Priority-Medium, Priority-High
cushon commentedon Jan 23, 2015
This sounds worthwhile. Checking both methods in a class wouldn't be difficult. We may need to exempt classes that only implement one, unless #157 is implemented.
Add a check for obviously inconsistent hashCode implementations.