(有坑)如何正确实现Comparator<T>接口

这篇博客讨论了由于Comparator<T>接口实现不正确导致的crash问题,提到了TimSort排序算法,它是JDK7开始采用的一种优化后的归并排序。TimSort对部分有序和倒序数组排序效率高,最坏情况下复杂度为O(n*log(n))。博客指出,Comparator的实现必须遵循特定约束,否则可能导致运行时异常。错误示例和解决方法也在文中给出。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近用户报告了一个crash,错误堆栈如下:

java.lang.IllegalArgumentException: Comparison method violates its general contract!
	at java.util.TimSort.mergeHi(TimSort.java:864)
	at java.util.TimSort.mergeAt(TimSort.java:481)
	at java.util.TimSort.mergeForceCollapse(TimSort.java:422)
	at java.util.TimSort.sort(TimSort.java:219)
	at java.util.TimSort.sort(TimSort.java:169)
	at java.util.Arrays.sort(Arrays.java:2010)
	at java.util.Collections.sort(Collections.java:1883)
	at com.xxx.model.c.a(Unknown Source)
	at com.xxx.view.de.doInBackground(Unknown Source)
	at android.os.AsyncTask$2.call(AsyncTask.java:288)
	at java.util.concurrent.FutureTask.run(FutureTask.java:237)
	at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
	at java.lang.Thread.run(Thread.java:841)


这个app运行了一年多还是第一次碰到这个crash。TimSort又是什么鬼?

简单的讲TimSort是一个优化后的merge sort,比原来的merge sort更稳定、更快。

两大特点:

1. 对已接近排序和倒序的数组排序速度异常快。

2. 最差情况仍是O(n*log(n))

JDK7的排序算法实现改为TimSort。java.util.TimSort的类注释。

/**
 * A stable, adaptive, iterative mergesort that requires far fewer than
 * n lg(n) comparisons when running on partially sorted arrays, while
 * offering performance comparable to a traditional mergesort when run
 * on random arrays.  Like all proper mergesorts, this sort is stable and
 * runs O(n log n) time (worst case).  In the worst case, this sort requires
 * temporary storage space for n/2 object references; in the best case,
 * it requires only a small constant amount of space.
 *
 * This implementation was adapted from Tim Peters's list sort for
 * Python, which is described in detail here:
 *
 *   http://svn.python.org/projects/python/trunk/Objects/listsort.txt
 *
 * Tim's C code may be found here:
 *
 *   http://svn.python.org/projects/python/trunk/Objects/listobject.c
 *
 * The underlying techniques are described in this paper (and may have
 * even earlier origins):
 *
 *  "Optimistic Sorting and Information Theoretic Complexity"
 *  Peter McIlroy
 *  SODA (Fourth Annual ACM-SIAM Symposium on Discrete Algorithms),
 *  pp 467-474, Austin, Texas, 25-27 January 1993.
 *
 * While the API to this class consists solely of static methods, it is
 * (privately) instantiable; a TimSort instance holds the state of an ongoing
 * sort, assuming the input array is large enough to warrant the full-blown
 * TimSort. Small arrays are sorted in place, using a binary insertion sort.
 *
 * @author Josh Bloch
 */


具体算法原理这里不做细究,有兴趣的可以研究一下上面注释中的链接或者论文。

解决方法为在实现Comparator<T>接口时,必须严格遵循实现约束,否则会导致运行时异常。 

具体约束为:

  1. sgn(compare(x, y)) == -sgn(compare(y, x)) for all x and y
  2. ((compare(x, y)>0) && (compare(y, z)>0)) implies compare(x, z)>0.
  3. compare(x, y)==0 implies that sgn(compare(x, z))==sgn(compare(y, z)) for all z.

 

错误示例:(JDK6下运行正常,JDK7下会crash)

public class XXXComparator implements Comparator<SomeModel> {

    // 当lhs==rhs时,compare(lhs,rhs)== -1, compare(rhs, lhs)==-1 违背约束1
    @Override
  public int compare(SomeModel lhs, SomeModel rhs) {
        if (rhs.value < lhs.value) {
            return 1;
        } else {
            return -1;
        }
    }

} 


参考: 

  1. http://docs.oracle.com/javase/7/docs/api/java/util/Comparator.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值