Skip to content Skip to sidebar Skip to footer

Fatal Exception: Java.lang.illegalargumentexception: Comparison Method Violates Its General Contract

I know there many similar questions and I have received big help by reading answers to those questions, however I am not able to see how is my client facing this problem. And there

Solution 1:

You have a possible inconsistency when comparing a null "sample" to a non-null sample with a null timestamp.

Sample a = null;
Sample b = new Sample(null);

bsc.compare(a, b); // -> 1, a > b
bsc.compare(b, a); // -> 1, b > a

First, you should replace the Date in your sample class with Instant if at all possible, and then make your life simpler by saying this:

public static final Comparator<Sample> ORDER_BY_TIMESTAMP =
  Comparator.nullsLast(Comparator.comparing(
      Sample::getDateTime,
      Comparator.nullsLast(Comparator.naturalOrder())
  );

If you can rule out null values, even simpler:

Comparator.comparing(Sample::getDateTime);

Solution 2:

I was missing some conditional for some cases and this is how I was able to solve my problem.

    private static class BiologySamplesComparator implements Comparator<BiologySample>, Serializable {
        @Override
        public int compare(BiologySample left, BiologySample right) {
            if (left == null) {
                if (right == null) {
                    return 0;
                } else {
                    return 1;
                }
            } else if (right == null) {
                return -1;
            } else if (left == right) {
                return 0;
            }
            if (left.getSampleDateTime() == null) {
                if (right.getSampleDateTime() == null) {
                    return 0;
                } else {
                    return 1;
                }
            } else if (right.getSampleDateTime() == null) {
                return -1;
            } else if (left.getSampleDateTime() == right.getSampleDateTime()) {
                return 0;
            }

            return right.getSampleDateTime().compareTo(left.getSampleDateTime());
        }
    }

courtesy of Why does my compare methd throw IllegalArgumentException sometimes?


Post a Comment for "Fatal Exception: Java.lang.illegalargumentexception: Comparison Method Violates Its General Contract"