Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I be concerned about this compareTo/equals/hashCode implementation?

I'm in the middle of QA'ing a bunch of code and have found several instances where the developer has a DTO which implements Comparable. This DTO has 7 or 8 fields in it. The compareTo method has been implemented on just 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:

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

and finally the hashcode method implementation is:

return field1.hashCode;

field1 should never be null and will be unique across these objects (i.e. we shouldn't get two objects with the same field1).

So, the implementations are consistent which is good, but should I be concerned that only one field is used? Is this unusual? Is it likely to cause problems or confuse other developers? I'm thinking of the scenario where a list of these objects are passed around and another developer uses a Map or Set of somesort and gets unusual behaviour from these objects. Any thoughts appreciated. Thanks!

like image 408
Chris Knight Avatar asked Dec 19 '25 04:12

Chris Knight


1 Answers

I suspect that this is a case of "first use wins" - someone needed to sort a collection of these objects or put them in a hash map, and they only cared about the date. The easiest way of implementing that was to override equals/hashCode and implement Comparable<T> in the way you've said.

For specialist sorting, a better approach would be to implement Comparator<T> in a different class... but Java doesn't have any equivalent class for equality testing, unfortunately. I consider it a major weakness in the Java collections, to be honest.

Assuming this really isn't "the one natural and obvious comparison", it certainly smells in terms of design... and should be very carefully document.

like image 154
Jon Skeet Avatar answered Dec 20 '25 20:12

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!