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