java - Comparison method violates its 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?
you need return 0 on equal objects.
if ( tas1.order < tas2.order ){ return -1; } else if ( tas1.order == tas2.order ){ return 0; } else { return 1; }
you can read here more
Comments
Post a Comment