Java 列表排序:有没有办法让列表像 TreeMap 一样自动排序? [英] Java List Sorting: Is there a way to keep a list permantly sorted automatically like TreeMap?

查看:25
本文介绍了Java 列表排序:有没有办法让列表像 TreeMap 一样自动排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Java 中,您可以使用项目构建一个 ArrayList,然后调用:

In Java you can build up an ArrayList with items and then call:

Collections.sort(list, comparator);

有没有像TreeMap那样在列表时传入Comparator,创建?

Is there anyway to pass in the Comparator at the time of list, creation like you can do with TreeMap?

目标是能够将一个元素添加到列表中,而不是将其自动附加到列表的末尾,列表将根据 Comparator 保持其自身的排序并插入新的Comparator 确定的索引处的元素.所以基本上列表可能必须根据添加的每个新元素重新排序.

The goal is to be able add an element to the list and instead of having it automatically appended to the end of the list, the list would keep itself sorted based on the Comparator and insert the new element at the index determined by the Comparator. So basically the list might have to re-sort upon every new element added.

无论如何,是否可以使用 Comparator 或其他类似方法以这种方式实现这一目标?

Is there anyway to achieve this in this way with the Comparator or by some other similar means?

推荐答案

你可以改变 ArrayList 的行为

You can change the behaviour of ArrayList

List<MyType> list = new ArrayList<MyType>() {
    public boolean add(MyType mt) {
         super.add(mt);
         Collections.sort(list, comparator);
         return true;
    }
}; 

注意:PriorityQueue 不是 List,如果你不关心它是什么类型的集合,最简单的方法是使用 TreeSet,它就像一个 TreeMap,但它是一个集合.PriorityQueue 唯一的优点是允许重复.

Note: a PriorityQueue is NOT a List, if you didn't care what type of collection it was, the simplest would be to use a TreeSet, which is just like a TreeMap but is a collection. The only advantage PriorityQueue has is to allow duplicates.

注意:对于大型集合,重新排序不是很有效,使用二分搜索和插入条目会更快.(但更复杂)

Note: resorting is not very efficient for large collections, Using a binary search and inserting an entry would be faster. (but more complicated)

很大程度上取决于您需要列表"去做.我建议您为 ArrayList、LinkedList、PriorityQueue、TreeSet 或其他排序集合之一编写 List 包装器,并实现将实际使用的方法.这样您就可以很好地了解集合的要求,并确保它适合您.

A lot depends on what you need the "list" to do. I suggest you write a List wrapper for an ArrayList, LinkedList, PriorityQueue, TreeSet, or one of the other sorted collections and implement the methods which will actually be used. That way you have a good understanding of the requirements for the collection and you can make sure it works correctly for you.

EDIT(2):因为人们对使用 binarySearch 非常感兴趣.;)

EDIT(2): Since there was so much interest in using binarySearch instead. ;)

List<MyType> list = new ArrayList<MyType>() {
    public boolean add(MyType mt) {
        int index = Collections.binarySearch(this, mt);
        if (index < 0) index = ~index;
        super.add(index, mt);
        return true;
    }
};

这篇关于Java 列表排序:有没有办法让列表像 TreeMap 一样自动排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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