Collections.sort是否保持等于元素的顺序? [英] Does Collections.sort keep order on equal elements?

查看:707
本文介绍了Collections.sort是否保持等于元素的顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个按日期参数排序的对象列表,并希望按类别参数重新排序,但将日期顺序保留在类别中。

I have a list of objects ordered by a date parameter and want to reorder them by category parameter, but keeping the date order within the category.

这足够或者我必须实现考虑相同类别的对象的日期的比较器。

Is something like this enough or do I have to implement a comparator that takes on account the date for objects of the same category?

// sort the list by category asc(, date asc )
Collections.sort((List<Object>)entries, new Comparator<Object>() {

    @Override public int compare(Object elementA, Object elementB) {
        return elementA.category.compareTo(elementB.category); // what happens when elementA.category.equals(elementB.category)?
    }

});


推荐答案

问题中的代码会做你需要的to, Collections.sort()会保留等于元素的顺序。

The code in your question will do what you need it to, since Collections.sort() does preserve the order of equal elements.

http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#sort(java.util.List,%20java.util.Comparator) =nofollow>文档:

From the documentation:


这种方式可以保证稳定:等于元素不会重新排序

This sort is guaranteed to be stable: equal elements will not be reordered as a result of the sort.

换句话说,如果条目在 sort 之后,他们将按照 sort()之后的每个类别中的日期排序

In other words, if the entries are ordered by date before the sort(), they will stay ordered by date within each category after the sort().

如果你不想依赖原来的订单,你可以很容易地扩展你的比较器,首先比较类别,然后使用日期打破关系。

If you don't want to rely on the original ordering, you can easily extend your comparator to first compare the categories and then break ties using the dates.

这篇关于Collections.sort是否保持等于元素的顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆