本文介绍了与可比较的树列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
选项1:创建一个实现Comparable的列表,并在每次添加值时使用collections.sort(List l)对它进行排序。
选项2:创建一个TreeSet(保持自身的排序)
Option 1: Make a list which implements Comparable and sort it using collections.sort(List l) every time you add a value.Option 2: Make a TreeSet (which keeps itself sorted all the time).
哪一个会更快?我要求这是因为List给了我ListIterator的选项,我需要在我的case,因为它允许我添加一个元素,而迭代。
Which one will be faster? I am asking this because List gives me the option of ListIterator which I need in my case, since it lets me add an element while iterating.
推荐答案
最重要的区别:
Criterion | List with Collections.sort | TreeSet
----------------+----------------------------+---------
cost of adding | O(n log n) | O(log n)
equal sort keys | permitted | eliminated as duplicates
iteration | bidirectional, can insert | unidirectional, can not insert
在迭代时插入元素,而不会得到 ConcurrentModificationException
,您可以:(E e:new ArrayList< E>(集合))
To insert an element when iterating without getting a ConcurrentModificationException
, you can do:
for (E e : new ArrayList<E>(collection)) {
// some other code
collection.add(anotherE);
}
这篇关于与可比较的树列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!