0

I have below code-

Stream.of(objects).sorted((o1,o2) -> {
  if (o1.getIsXXXTrue()) return -1;
  if (o2.getIsXXXTrue()) return 1;
  return (o2.getScore() - o1.getScore());
}).toArray(MyObject[]::new);

Intermittently for some set of objects I am getting below exception-

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

I read some similar article and came to know that it might be because transitivity contract is breaking in comparison code(A > B and B > C but A is not greater than C). I tried to dry run with different values of objects but couldn't find any case where transitivity might break! Can you you guys help me with what might be wrong with this code! Is it about transitivity or any other contract might be breaking. Any leads to find the problem and how to fix it are appreciated. Thank you.

ValarDohaeris
  • 639
  • 1
  • 6
  • 21
  • 2
    `var obj1 = new MyObject(true); var obj2 = new MyObject(true); obj1.compareTo(obj2) == obj2.compareTo(obj1)` so both objects are "smaller" than the respective other object. Also, an object is always smaller (or bigger) than itself: `obj1.compareTo(obj1) == -1`. It's like saying "1 != 1", "1 < 1" or "1 < 2 && 2 < 1" – knittl Feb 08 '23 at 12:23
  • 2
    Your comparison method must be symmetric. meaning if you do `compare(a, b)` and receive `1` as a result, `compare(b, a)` must return `-1`. You violated that contract because if `o1.getIsXXXTrue()` is true you always return `-1`. So imagine if both `o1` and `o2` return true on `getIXXXTrue()`, that would mean `compare(o1, o2)` to return `-1` and `compare(o2, o1)` also to return `-1`. So which one of those 2 objects should come first in the natural order? You basically programmed a comparator that sometimes says A is greater than B, but then also claims that B is greater than A. – OH GOD SPIDERS Feb 08 '23 at 12:27
  • 1
    Also https://stackoverflow.com/questions/11441666/java-error-comparison-method-violates-its-general-contract and many more – Didier L Feb 08 '23 at 12:48

0 Answers0