The cause of an weired exception of sort() in jdk1.7 and above

In jdk1.7 and above, The algorithm of sort had been changed from mergesort to timsort, (The further detail of this can be seen here)

The new sort() requires more specific compare conditions, the return type must contains negative integer(smaller), positive integer(bigger) and zero(equals),and it must fits these three requirements:

1) sgn(compare(x, y)) == -sgn(compare(y, x))

  This means that you can not define a compare method in comparator against the symmetry, if you stipulate object A is bigger than object B(or smaller or equals), then use the same comparator it must shows that  B is smaller than A;

2) (compare(x, y) >0) && (compare(y, z) >0) => compare(x, z) > 0

  This means that you can not against the transitivity when writing a compare() method;

3) compare(x, y)==0 => sgn(compare(y, z) == sgn(compare(y, z)

  Like this: A==B, then if A==C we must have B == C, this is the transitivity too;

so, if your code against these laws there is a possibility to throw out an exception "Exception in thread "main" java.lang.IllegalArgumentException: Comparison method violates its general contract!". The fucking point is that this exception somtimes may but sometines won't be checked out during compile, so we really shoule pay lots of attention during write a self define comprator.

 

posted @ 2016-03-18 16:15  SunCosmo  阅读(146)  评论(0)    收藏  举报