Getting java.lang.IllegalArgumentException: Comparison method violates its general contract! with a sort algo that should be 100% stable

StackOverflow https://stackoverflow.com/questions/21164931

Вопрос

No idea how this could ever be unstable. This works fine on most cases, but throws IllegalArgumentException with some queries.

That is all, can't think of more relevant details.

private static void sortSearchResults(List<Map> l){
        Comparator<Map> comp = new Comparator<Map>(){
            public int compare(Map a,Map b){
                int aa=0,ba=0,as=0,bs=0;
                try{
                    aa = Integer.parseInt(""+a.get("activity"));

                }catch(Exception ex){
                }
                try{
                    ba = Integer.parseInt(""+b.get("activity"));
                }catch(Exception ex){
                }
                try{
                    as = Integer.parseInt(""+a.get("searchscore"));

                }catch(Exception ex){
                }
                try{
                    bs = Integer.parseInt(""+b.get("searchscore"));
                }catch(Exception ex){
                }


                if(as>bs)
                    return -1;
                else if(bs<as)
                    return 1;
                else{
                    if(aa>ba)
                        return -1;
                    else if(aa<ba)
                        return 1;
                    else
                        return 0;
                }

            }
            public boolean equals(Object o){
                return o==this;
            }
        };
        Collections.sort(l,comp);
    }
Это было полезно?

Решение

if(as>bs)
    return -1;
else if(bs<as)
    return 1;

as>bs and bs<as mean exactly the same thing. You probably meant:

if(as<bs)
    return -1;
else if(as>bs)
    return 1;
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top