why does my compare method throw exception — Comparison method violates its general contract!

后端 未结 7 1723
别那么骄傲
别那么骄傲 2020-11-30 12:49

Why does this code

public class SponsoredComparator implements Comparator {

    public boolean equals(SRE arg0, SRE arg1){
        return arg0.g         


        
7条回答
  •  南方客
    南方客 (楼主)
    2020-11-30 12:55

    I suspect the problem occurs when neither value is sponsored. That will return 1 whichever way you call it, i.e.

    x1.compare(x2) == 1
    
    x2.compare(x1) == 1
    

    That's invalid.

    I suggest you change this:

    object1.getSponsored() && object2.getSponsored()
    

    to

    object1.getSponsored() == object2.getSponsored()
    

    in both places. I would probably actually extract this out a method with this signature somewhere:

    public static int compare(boolean x, boolean y)
    

    and then call it like this:

    public int compare(SRE object1, SRE object2) {
        return BooleanHelper.compare(object1.getSponsored(), object2.getSponsored());
    }
    

    That will make the code clearer, IMO.

提交回复
热议问题