GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — [java] OverrideBothEqualsAndHashCodeOnComparable should not be required for record classes · Issue #6072 · pmd/pmd

[java] OverrideBothEqualsAndHashCodeOnComparable should not be required for record classes #6072

New issue
Copy link
New issue
Copy link
Closed
#6081
Closed
[java] OverrideBothEqualsAndHashCodeOnComparable should not be required for record classes#6072
#6081
Copy link
Labels
a:false-positivePMD flags a piece of code that is not problematic
Milestone
7.19.0

Description

@Juneezee
Juneezee
opened on Sep 18, 2025
Issue body actions

Affects PMD Version:

7.17.0

Rule:

OverrideBothEqualsAndHashCodeOnComparable: https://docs.pmd-code.org/pmd-doc-7.17.0/pmd_rules_java_errorprone.html#overridebothequalsandhashcodeoncomparable

Description:

Record classes have their hashCode and equals methods automatically implemented.

IntelliJ IDEA’s inspection ComparableImplementedButEqualsNotOverridden does not flag record classes as violations. Since OverrideBothEqualsAndHashCodeOnComparable was originally inspired by IDEA (#5837), PMD should also exclude record classes from this rule.

Image

Reference: https://docs.oracle.com/javase/specs/jls/se17/html/jls-8.html#jls-8.10.3
Reference: https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/Record.html#equals(java.lang.Object)

Code Sample demonstrating the issue:

Adapted from https://www.jetbrains.com/help/inspectopedia/ComparableImplementedButEqualsNotOverridden.html:

record Foo(int cm) implements Comparable<Foo> {
  @Override
  public int compareTo(Foo o) {
    if (cm == o.cm) {
      return 0;
    }
    return cm < o.cm ? -1 : 1;
  }
}

class Bar implements Comparable<Bar> {
  private final int cm;

  public Bar(int cm) {
    this.cm = cm;
  }

  @Override
  public int compareTo(Bar o) {
    if (cm == o.cm) {
      return 0;
    }
    return cm < o.cm ? -1 : 1;
  }
}

Expected outcome:

OverrideBothEqualsAndHashCodeOnComparable should not be required for record classes.

Running PMD through: Gradle

Activity

  1. Juneezee
    added
    a:false-positivePMD flags a piece of code that is not problematic
    on Sep 18, 2025
  2. UncleOwen commented on Sep 20, 2025

    @UncleOwen
    UncleOwen
    on Sep 20, 2025
    Member
    More actions

    I agree. records already have a sane .equals()/.hashCode(). We shouldn't be telling users to add custom implementations if the default is fine.

  3. adangel commented on Sep 21, 2025

    @adangel
    adangel
    on Sep 21, 2025
    Member
    More actions

    The key point here is

    if the default is fine.

    For the example given in this issue, it is fine: There is only one component, and this component is used within compareTo - so the implementation of compareTo "is consistent with equals".

    But given the following example:

    import module java.base;
    
    void main() {
      record MyRecord(String a, int b) implements Comparable<MyRecord> {
        public int compareTo(MyRecord other) {
          return b - other.b;
        }
      }
    
      List<MyRecord> data = Arrays.asList(new MyRecord("a", 1), new MyRecord("b", 1));
      IO.println("data size: " + data.size());
    
      Set<MyRecord> set = new HashSet<>(data);
      IO.println("set size: " + set.size());
    
      Set<MyRecord> sortedSet = new TreeSet<>(data);
      IO.println("sorted set: " + sortedSet.size());
    }

    If you run this (with java25), you'll get this output:

    data size: 2
    set size: 2
    sorted set: 1
    

    Which shows the effect of a compareTo implementation, that is not consistent with equals. As described in TreeSet, the equality of two elements in a ordinary Set (e.g. HashSet) is based on equals, but the equality in a sorted Set (e.g. TreeSet) is based on compareTo. If these two are not consistent, you'll get different results depending on which Set implementation you use.

    This is the whole point of the rule: Reminding developers to think about whether they use the elements in a sorted set and whether the compareTo and equals methods need to be consistent.

    For the above example, an equals (and hashCode) method can be added to the record, which makes it consistent:

        public boolean equals(Object o) {
            if (o == null || getClass() != o.getClass()) {
                return false;
            }
            return compareTo((MyRecord) o) == 0;
        }
    
        public int hashCode() {
          return b;
        }

    Now, both Set implementations behave the same (which means, they behave consistent) - they correctly eliminate duplicates in the same way.

    This is actually documented already in the rule (https://docs.pmd-code.org/latest/pmd_rules_java_errorprone.html#overridebothequalsandhashcodeoncomparable):

    Note 2: This rule also reports records that implement Comparable. While for records, equals() and hashCode() are generated, you still must make sure that compareTo() is consistent with equals().

    The question is now - what should a static code analyzer such as PMD do? Should we simply ignore records (records are nothing other than classes) (I guess, that is what JetBrains decided to do), should we improve the rule to really analyze the implementation of the compareTo method to figure out, if it is consistent with equals (which is a lot of effort and probably only feasible for simple compareTo methods), should we add a property so that users can deliberately ignore records, should we add an example (e.g. this example I've given) to make users understand the issue, should we add a separate rule "CompareToInRecordNotConsistentWithEquals?", should we suggest to suppress the rule in such cases ...?

    @UncleOwen You suggested in #6081 to simple ignore records - which basically means, we let PMD err on the side of false-negatives rather than producing false-positives. I guess, if we do this, we need to create a new issue here that describes the false-negative, that we from now on won't be able to detect.

  4. UncleOwen commented on Sep 21, 2025

    @UncleOwen
    UncleOwen
    on Sep 21, 2025
    Member
    More actions

    This is the whole point of the rule: Reminding developers to think about whether they use the elements in a sorted set and whether the compareTo and equals methods need to be consistent.

    I believe that might be the core of the issue. Is "You should think about this" really enough? In the general case, I think the confidence rate (that is: number of true positives / number of violations) of this rule is very high. But in this one special case, records implementing Comparable, I don't think it is as high as we'd like it to be. Do we agree on that?

    As to what to do next: Of course, fixing this rule properly or adding a new rule would be best. But I can't imagine how a proper solution would look like. Maybe verify that compareTo() looks at all the members? I don't know, looks brittle. But maybe worth investigating?

    But until we have a proper solution, I prefer not triggering a violation over what we are doing currently. That's what #6081 is doing. If you'd like, I can make this configurable. But I would turn the violations off by default.

  5. adangel commented on Oct 23, 2025

    @adangel
    adangel
    on Oct 23, 2025
    Member
    More actions

    @jsotuyod @oowekyala @zbynek Should we err on the false positive side or the false negative side in this case? What do you think?

  6. zbynek commented on Oct 23, 2025

    @zbynek
    zbynek
    on Oct 23, 2025
    Contributor
    More actions

    I think comparable records should be only reported if they override exactly one of equals and hashcode.

    Reacted by Clément Fournier
  7. adangel commented on Oct 24, 2025

    @adangel
    adangel
    on Oct 24, 2025
    Member
    More actions

    if they override exactly one of equals and hashcode

    Then this should be reported by OverrideBothEqualsAndHashcode, shouldn't it? Ah, ok, no: that rule doesn't report on comparable types.

    So, yes, that seems to be a reasonable middle ground.

    Other suggestions:

    • clearly say, when to use this rule: currently we way "if instances of these classes are used in collections". This should be "... sorted collections".
    • remove this rule from the quickstart ruleset. As the rule makes only sense, if you use sorted collections... so - it doesn't apply in the general case.

    @UncleOwen Could you update your PR #6081 to make sure, we have test cases for:
    a) no violation:

    record Foo(int a) implements Comparable<Foo> {
      public int compareTo(Foo f) {
        return 0;
      }
    }

    b) one violation:

    record Foo(int a) implements Comparable<Foo> {
      public int compareTo(Foo f) {
        return 0;
      }
      public int hashCode() {
        return 0;
      }
    }

    c) one violation:

    record Foo(int a) implements Comparable<Foo> {
      public int compareTo(Foo f) {
        return 0;
      }
      public boolean equals(Object o) {
        return false;
      }
    }

    d) no violation:

    record Foo(int a) implements Comparable<Foo> {
      public int compareTo(Foo f) {
        return 0;
      }
      public int hashCode() {
        return 0;
      }
      public boolean equals(Object o) {
        return false;
      }
    }

    Thanks!

  8. adangel
    added this to the 7.19.0 milestone on Nov 27, 2025
  9. adangel
    added 2 commits that reference this issue on Nov 27, 2025

    [doc] Update release notes (pmd#6072, pmd#6081)

    f031cee

    [java] Fix pmd#6072: OverrideBothEqualsAndHashCodeOnComparable should…

    2f4d5a4
  10. adangel
    closed this as completedin 2f4d5a4on Nov 27, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    a:false-positivePMD flags a piece of code that is not problematic

    Type

    No type

    Projects

    No projects

      Milestone

      • 7.19.0

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions

      You are visitor 01402775 — GeezerVison does not store the pages you look up.
      Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.