124697
124697

Reputation: 21893

Can't see why i am getting "Comparison method violates its general contract" error

Comparison method violates its general contract

I am sorting by rating which is a double. Can anyone see why i am getting this error?

Collections.sort(productsMasterList, new Comparator<Product>() {
    @Override
    public int compare(Product o1, Product o2) {
        final double rating1 = o1.getRating();
        final double rating2 = o2.getRating();
        boolean realisticRating1 = rating1 < 4.8;
        boolean realisticRating2 = rating2 < 4.8;
        return rating1 > rating2 && realisticRating1 ? -1 : rating2 > rating1 && realisticRating2 ? 1 : 0;
    }
});

edit: This is not a duplicate because it is very specific to me. i have seen other answers but i still can't figure out why i am getting this error, my code seems like it should work fine

Upvotes: 2

Views: 106

Answers (1)

ruakh
ruakh

Reputation: 183446

Consider these three ratings:

1
3
5    // unrealistic

According to your comparator, unrealistic ratings compare equal to all other ratings; so even though 1 and 3 are not equivalent to each other, they are both equivalent to 5. So your comparator doesn't implement a transitive relation, so the client of your comparator can't get consistent results; everything comes out wonky.

Upvotes: 8

Related Questions