Bad practice. The class defines compareTo (...) and uses Object.equals ()

Satisfying what needs to be done for the listed methods

public final int compareTo(final FieldDTO o) { return o.available.compareTo(this.available); 

exception of its exception in line 2 Bad practice - the class defines compareTo (...) and uses Object.equals () 16 days
the field defines compareTo (FieldDTO) and uses Object.equals ()

I don’t know how I should deal with this. Thanks in advance.

+4
source share
4 answers

If you define compareTo , you should at least define equals

 boolean equals(it) { return compareTo(it) == 0; } 

otherwise, you will have strange problems when you put your object in Map and Set s. As a general rule, hashCode is also a good practice.

+7
source

This is the documentation from FindBugs :

Eq: The class defines compareTo (...) and uses Object.equals () (EQ_COMPARETO_USE_OBJECT_EQUALS)

This class defines the compareTo (...) method, but inherits its equals () method from java.lang.Object. Typically, the value of compareTo should return zero if and only if equals returns true. If this is broken, strange and unpredictable failures will occur in classes such as PriorityQueue. In Java 5, the PriorityQueue.remove method uses compareTo, while in Java 6 the equals method is used.

From the JavaDoc for the compareTo method in the Comparable interface:

Highly recommended, but not strictly required, to (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. Recommended language: "Note: this class has a natural ordering that is incompatible with peers."

So, you need to implement the equals method, thereby overriding the default implementation from Object .

+5
source

you need to override the class methods equals () and hashCode (). Use the generated IDE code for them, it will pull out all the attributes of the Object and create a method for you.

In the eclipse IDE:

  • Right click class
  • Choose source
  • Create hashCode () and equals () ...
+3
source

Your class seems to implement the Comparable interface.

JavaDocs are strict here: if you use your own compareTo() method, it should return 0 only if the equals() method returns true .

So:

 (x.compareTo==0) == (x.equals). 
0
source

Source: https://habr.com/ru/post/1482256/


All Articles