Should I be concerned about the implementation of compareTo / equals / hashCode?

I am in the middle of QA with a bunch of code and found some examples where a developer has a DTO that implements Comparable. There are 7 or 8 fields in this DTO. The compareTo method was implemented in only one field:

private DateMidnight field1;  //from Joda date/time library

public int compareTo(SomeObject o) {
   if (o == null) {
      return -1;
   }
   return field1.compareTo(o.getField1());
}

Similarly, the equals method is overridden and basically boils down to the following:

return field1.equals(o.getField1());

and finally, the implementation of the hashcode method:

return field1.hashCode;

field1should never be zero and will be unique to these objects (i.e. we should not receive two objects with the same field1).

, , , , ? ? ? , , Map Set somesort . . !

+3
4

, " " - - -, . - equals/hashCode Comparable<T> , .

Comparator<T> ... , , Java . , Java.

, " ", , , ... .

+5

, :

http://download.oracle.com/javase/6/docs/api/java/lang/Comparable.html

, null - , e.compareTo(null) NullPointerException, e.equals(null) false.

, equals NPE equals(null) , false (, , "" ).

?

, . , / "" / :

  • // == , .
  • // == .
+2

, 1 . , . , . .

+2

, . .

- - .

, , field1 , . 1 " " ,

+1

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


All Articles