java - Comparison method throws general contract exception -


below block of code results in exception indicated,

code :

            collections.sort( arraylist, new comparator()             {                 public int compare( object o1, object o2 )                 {                 typeadaptersort tas1 = ( typeadaptersort ) o1;                 typeadaptersort tas2 = ( typeadaptersort ) o2;                 if ( tas1.order < tas2.order )                     return -1;                 else                     return 1;                 }             } ); 

exception :

java.lang.illegalargumentexception: comparison method violates general contract!                     @ java.util.timsort.mergelo(timsort.java:747)                     @ java.util.timsort.mergeat(timsort.java:483)                     @ java.util.timsort.mergeforcecollapse(timsort.java:426)                     @ java.util.timsort.sort(timsort.java:223)                     @ java.util.timsort.sort(timsort.java:173)                     @ java.util.arrays.sort(arrays.java:659)                     @ java.util.collections.sort(collections.java:217) 

when run same code standalone program, issue never occurs. issue comparator here? there way reproduce issue in standalone code?

this issue occurs on java 1.7 there has been change in implementation on arrays.sort & collections.sort. how change above code avoid issue?. also, how reproduce issue in standalone code?

the comparator doesn't obey general contract. @ this:

if ( tas1.order < tas2.order )     return -1; else     return 1; } 

now consider 2 objects have same order. comparing them should return 0.

you'd better off delegating integer.compare if you're using java 7:

return integer.compare(tas1.order, tas2.order); 

or if you're using earlier version:

return tas1.order == tas2.order ? 0      : tas1.order < tas2.order ? -1      : 1; 

Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -