-1

Hey guys I have this code to compare by duration but I keep getting this error:

Fatal Exception: java.lang.IllegalArgumentException Comparison method violates its general contract!

Here is my code:

Collections.sort(list, new Comparator<MyProduct>() {

    @Override
    public int compare(MyProduct lhs, MyProduct rhs) {
        Integer lDuration = (lhs != null ? lhs.getDuration() :0);
        Integer rDuration = (rhs != null ? rhs.getDuration() :0);

        return lDuration.compareTo(rDuration);
    }
});
klutt
  • 30,332
  • 17
  • 55
  • 95

1 Answers1

0

You are violating the requirements of consistency with equals:

When we say that the ordering imposed by c on S is consistent with equals, we mean that the quotient for the ordering is the equivalence relation defined by the objects' equals(Object) method(s):

{(x, y) such that x.equals(y)}

You are saying that null is equal to an instance with zero duration, which it is not, because zeroDuration.equals(null) is false (or, at least, it should be), and null.equals(zeroDuration) results in an exception.

You should decide either to put all null elements first, or all null elements last.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243