Skip to content

Check that equals() and hashCode() read the same fields #35

Closed

Description

@cushon

Original issue created by cpovirk@google.com on 2012-08-06 at 08:48 PM


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.

Activity

  1. cushon commented on Oct 31, 2014

    @cushon
    CollaboratorAuthor

    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

  2. cushon commented on Jan 23, 2015

    @cushon
    CollaboratorAuthor

    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.

  3. added a commit that references this issue on Sep 12, 2018
    e8cf0b5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions