Java Collection Sort: Issue while sorting list -
this question has been asked many times understood should return 0 1 , -1 still getting exception
java.lang.illegalargumentexception: comparison method violates general contract! @ java.util.timsort.mergehi(timsort.java:895) @ java.util.timsort.mergeat(timsort.java:512) @ java.util.timsort.mergeforcecollapse(timsort.java:453) @ java.util.timsort.sort(timsort.java:250) @ java.util.arrays.sort(arrays.java:1512) @ java.util.arraylist.sort(arraylist.java:1454) @ java.util.collections.sort(collections.java:175)
code snippet
collections.sort(list, new comparator < employee > () { public int compare(employee emp1, employee emp2) { int compareval = 0; int returnval = 0; try { if (emp1 == emp2) { returnval = 0; } else { if (empname.equalsignorecase(constant.emp_id)) { if (emp1.getempcode() != null && emp2.getempcode() != null) { compareval = emp1.getempcode().comparetoignorecase(emp2.getempcode()); } } else { compareval = 5; } if (compareval > 0) { returnval = 1; } else if (compareval < 0) { returnval = -1; } else if (compareval == 0) { returnval = 0; } } } catch (exception e) { e.printstacktrace(); } return returnval; } });
it has version of jdk. if in jdk6, maybe have problem in jdk 7 described you, because implementation method in jdk 7 has been changed.
look @ this:
description: sorting algorithm used java.util.arrays.sort , (indirectly) java.util.collections.sort has been replaced. new sort implementation may throw illegalargumentexception if detects comparable violates comparable contract. previous implementation silently ignored such situation. if previous behavior desired, can use new system property, java.util.arrays.uselegacymergesort, restore previous mergesort behaviour.
i don't know reason. however, if add code before use sort. ok.
system.setproperty("java.util.arrays.uselegacymergesort", "true");
Comments
Post a Comment