问题
Wondering what needs to be done for listed method
public final int compareTo(final FieldDTO o) {
return o.available.compareTo(this.available);
its throwing exception on line 2 stating
Bad practice - Class defines compareTo(...) and uses Object.equals() 16 days
field defines compareTo(FieldDTO) and uses Object.equals()
Not sure how should i handle this. Thanks in advance.
回答1:
If you define compareTo you should at least define equals
boolean equals(it) {
return compareTo(it) == 0;
}
otherwise you will get strange problems when you put your object in Maps and Sets. It is generally good practice to also define hashCode.
回答2:
This is the documentation from FindBugs:
Eq: Class defines compareTo(...) and uses Object.equals() (EQ_COMPARETO_USE_OBJECT_EQUALS)
This class defines a compareTo(...) method but inherits its equals() method from java.lang.Object. Generally, the value of compareTo should return zero if and only if equals returns true. If this is violated, weird and unpredictable failures will occur in classes such as PriorityQueue. In Java 5 the PriorityQueue.remove method uses the compareTo method, while in Java 6 it uses the equals method.
From the JavaDoc for the compareTo method in the Comparable interface:
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."
So it seems you need to implement the equals method thus overriding the default implementation from Object.
回答3:
you need to override Object class equals() and hashCode() methods. Use IDE generated code for these, it will pull all the Object attributes and creates method for you.
On eclipse IDE:
- Right click on the class
- Select Source
- Generate hashCode() and equals()...
回答4:
Your class, as it seems, implements the Comparable interface.
JavaDocs are strict here: if you are using your own compareTo() method, it must return a 0 only if the equals() method returns true.
So:
(x.compareTo==0) == (x.equals).
来源:https://stackoverflow.com/questions/16701047/bad-practice-class-defines-compareto-and-uses-object-equals