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

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

问题描述

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

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

Collections.sort(list,comparator);

在创建列表的时候,有没有传入Comparator,像TreeMap一样?目标是能够向列表中添加一个元素,而不是将其自动附加到列表的末尾,列表将根据比较器保持自己的排序,并将新元素插入由比较器确定的索引。因此,基本上列表可能必须对添加的每个新元素重新排序。

Is there anyway to pass in the Comparator at the time of List creation like you can do with TreeMap? 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?

感谢。

推荐答案

/ p>

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不是列表,如果你不在乎什么类型的集合,最简单的是使用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 a 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.

编辑(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天全站免登陆