java - CompareTo is transitive -


i have pojo looking this:

public class pojo implements comparable<pojo> {      private string type;      private string journalid;      private date bookingdate;      private long account;      private string description;      private bigdecimal debit;      private bigdecimal credit;      .... } 

and want sort list of these pojos. compareto method looks this:

@override public int compareto(efdisjournal other) {     int = this.type.compareto(other.type);     if (i != 0)         return i;     if (this.bookingdate != null && other.bookingdate != null)         = this.bookingdate.compareto(other.bookingdate);     if (i != 0)         return i;     if (this.journalid != null && other.journalid != null)         = this.journalid.compareto(other.journalid);     if (i != 0)         return i;     return this.account.compareto(other.account); } 

if run sort compareto method, java.lang.illegalargumentexception: comparison method violates general contract error. did google bit , think happens because of fields null on comparison. yet have no idea how solve or if right why error appears.

the comparison should work this: 1st compare type, compare bookingdate, 3rd compare journalid , @ last compare account. comparisons should ascending.

  • type never null
  • bookingdate may null
  • journalid may null
  • account never null

edit:

sadly not able implement method, order needed. yet, solved problem had, because stored procedure yielded 2 resultsets, of second order needed, thing had use 2nd resultset instead of first.

you need deal case one instance has null bookingdate, , other has non-null bookingdate. should decide whether things null bookingdate should sorted before or after things non-null bookingdate, , write compareto appropriately. (and journalid too.) can order sorts consistently.

for instance:

@override public int compareto(efdisjournal other) {     int = this.type.compareto(other.type);     if (i != 0) {         return i;     }     if ((this.bookingdate==null) ^ (other.bookingdate==null)) {         return (this.bookingdate==null ? -1 : 1);     }     if (this.bookingdate != null && other.bookingdate != null) {         = this.bookingdate.compareto(other.bookingdate);     }     if (i != 0) {         return i;     }     if ((this.journalid==null) ^ (other.journalid==null)) {         return (this.journalid==null ? -1 : 1);     }     if (this.journalid != null && other.journalid != null) {         = this.journalid.compareto(other.journalid);     }     if (i != 0) {         return i;     }     return this.account.compareto(other.account); } 

Comments

Popular posts from this blog

neo4j - finding mutual friends in a cypher statement starting with three or more persons -

php - How to remove letter in front of the word laravel -

minify - Minimizing css files -