-5

Getting below bug in findbug: EQ_COMPARETO_USE_OBJECT_EQUALS Below is the statement:

public int compareTo (OPVest vesting)
{
int c = this.Date.compareTo (vest.Date);
if (c != 0)
return c;

return this.Id - vest.segmentId;
}

Kindly suggest.

Juned Ahsan
  • 67,789
  • 12
  • 98
  • 136
user2144684
  • 103
  • 2
  • 12

3 Answers3

1

from java Docs

It is strongly recommended, but not strictly required that (x.compareTo(y)==0) == (x.equals(y)). Generally speaking, any class that implements the Comparable interface and violates this condition should clearly indicate this fact. The recommended language is "Note: this class has a natural ordering that is inconsistent with equals."

override equals - and hashCode

and you have some errors in code

 public int compareTo (OPVest vesting)
   {
      int c = this.Date.compareTo (vesting.Date);
       if (c != 0)
         return c;

        return this.Id - vesting.segmentId;
   }
PSR
  • 39,804
  • 41
  • 111
  • 151
0

Basically FindBugs is complaining about the fact that your compareTo() method is inconsistent with equals().

Your compareTo method should return zero, only if this equals the operand.

Possible fixes are :

  • Overriding equals() and hashCode() to be in line with what your compareTo() method does.
  • Using a Comparator rather than making this class Comparable, and documenting it to be inconsistent with equals()
  • Document this class to have a natural ordering that is inconsistent with equals(). I guess this won't make FindBugs happy, but it is a valid, yet discouraged, possibility.

As a side remark : be sure that if you return the result of an addition or substraction for compareTo() that you cannot get an overflow.

bowmore
  • 10,842
  • 1
  • 35
  • 43
0

Generally, the value of compareTo() should return zero if and only if equals() returns true. Failure to meet this, may cause unpredictable behaviour in other Java classes. Since the default equals() method uses different criteria to compare objects, be sure to override equals() if you override compareTo().

Ander Juaristi
  • 328
  • 3
  • 12