1

I'm trying to reproduce the issue mentioned in this post: Comparison method violates its general contract

What I do is making a parent class A, which has it's own compareTo() function, then I made a class B inherits from class A, and overrides the compareTo() like:

public int compareTo(Object o) { return super.compareTo(o);}

And another class C also inherits from class A, and overrides the compareTo() as:

public int compareTo(Object o) { return -super.compareTo(o);}

So I made a list of bunch of class B/C objects, and use Collections.sort() to sort them, however I didn't see the Exception mentioned in previous post, the sort function runs well, but it gives me a weird order.

Could someone help me here? Thanks.

Community
  • 1
  • 1
hj690
  • 25
  • 1
  • 5
  • How do you even expect that ordering to work? Overriding `compareTo` frankly sounds like it is _inherently_ doomed to failure. – Louis Wasserman Jun 20 '16 at 22:05
  • @LouisWasserman Oh, actually I was trying to re-produce the issue mentioned in that post, I think the way I override `compareTo` should reproduce the Exception, but it didn't. – hj690 Jun 20 '16 at 22:07
  • You are not even a little bit guaranteed that that exception will appear with any given test data or even, necessarily, at all depending on your Java version. – Louis Wasserman Jun 20 '16 at 22:08

2 Answers2

5

The "Comparison method violates its general contract" exception is thrown on a best-effort basis: if the sort algorithm sees anything obvious it will throw the exception, but it won't do any extra work to test your comparison method. You may just have gotten lucky with your test data.

It is perfectly normal for an exception not to be thrown if you get lucky, but that exception may appear at any moment later.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
1

As the documentation for Collections.sort states, this exception is optional:

IllegalArgumentException - (optional) if the implementation detects that the natural ordering of the list elements is found to violate the Comparable contract

Implementations are not required to throw it.

Also note that

Implementation Note:
This implementation defers to the List.sort(Comparator) method using the specified list and a null comparator.

and the documentation for List.sort contains the same note that this exception is optional.

Hulk
  • 6,399
  • 1
  • 30
  • 52