Sorting throws java.lang.IllegalArgumentException: Comparison method violates its general contract -


i have method contains 2 comparators sorting items price.

this works fine 90% of time throws exception in title. know why

void sort(     collections.sort(masterlist, new comparator<item>() {     @override     public int compare(item o1, item o2) {         try {             if (o1.getpricelevel() == 999 && o1.getpricelevel() < o2.getpricelevel()) {                 return 1;             }             if (o2.getpricelevel() == 999) {                 return -1;             }             return double.compare(o1.getpricelevel(), o2.getpricelevel());         } catch (exception e) {             e.printstacktrace();             return 0;         }      }     }); //null pointer happens on line below     collections.sort(masterlist, collections.reverseorder(new comparator<item>() {     @override     public int compare(item o1, item o2) {         try {             if (o1.getpricelevel() == 999 || o2.getpricelevel() == 999) {                 return 1;             }             return double.compare(o1.getpricelevel(), o2.getpricelevel());          } catch (exception e) {             e.printstacktrace();             return 0;         }     }     })); } 

edit: stacktrace

java.lang.illegalargumentexception: comparison method violates general contract! @ java.util.timsort.mergelo(timsort.java:743) @ java.util.timsort.mergeat(timsort.java:479) @ java.util.timsort.mergecollapse(timsort.java:406) @ java.util.timsort.sort(timsort.java:210) @ java.util.timsort.sort(timsort.java:169) @ java.util.arrays.sort(arrays.java:2038) @ java.util.collections.sort(collections.java:1891) 

this check in timsort algorithm used java7 - validates comparator method valid ( e.g. symetric- == b && b == )

your equals case invalid (returning 0) - depends on order arguments given if 1 element null. try handle null values explicitly before doing else e.g.:

if(o1 == null || o2 == null) {     return 0; }  

Comments

Popular posts from this blog

Android layout hidden on keyboard show -

google app engine - 403 Forbidden POST - Flask WTForms -

c - Why would PK11_GenerateRandom() return an error -8023? -