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


i'm in middle of qa'ing bunch of code , have found several instances developer has dto implements comparable. dto has 7 or 8 fields in it. compareto method has been implemented on 1 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 equals method overridden , boils down to:

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

and hashcode method implementation is:

return field1.hashcode; 

field1 should never null , unique across these objects (i.e. shouldn't 2 objects same field1).

so, implementations consistent good, should concerned 1 field used? unusual? cause problems or confuse other developers? i'm thinking of scenario list of these objects passed around , developer uses map or set of somesort , gets unusual behaviour these objects. thoughts appreciated. thanks!

i suspect case of "first use wins" - needed sort collection of these objects or put them in hash map, , they cared date. easiest way of implementing override equals/hashcode , implement comparable<t> in way you've said.

for specialist sorting, better approach implement comparator<t> in different class... java doesn't have equivalent class equality testing, unfortunately. consider major weakness in java collections, honest.

assuming isn't "the 1 natural , obvious comparison", smells in terms of design... , should document.


Comments

Popular posts from this blog

Add email recipient to all new Trac tickets -

400 Bad Request on Apache/PHP AddHandler wrapper -

php - Change action and image src url's with jQuery -