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.
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.
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;
}
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 :
equals()
and hashCode()
to be in line with what your compareTo()
method does.Comparator
rather than making this class Comparable
, and documenting it to be inconsistent with equals()
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.
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()
.