jeudi 4 juin 2015

Java Collection Sort: Issue while sorting list

This question has been asked many times what i understood is it should return 0 as well with 1 and -1 but still I am getting this exception

java.lang.IllegalArgumentException: Comparison method violates its general contract!  
        at java.util.TimSort.mergeHi(TimSort.java:895)  
        at java.util.TimSort.mergeAt(TimSort.java:512)  
        at java.util.TimSort.mergeForceCollapse(TimSort.java:453)  
        at java.util.TimSort.sort(TimSort.java:250)  
        at java.util.Arrays.sort(Arrays.java:1512)  
        at java.util.ArrayList.sort(ArrayList.java:1454)  
        at 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;

});

Aucun commentaire:

Enregistrer un commentaire