aps*_*aps 6 java collections comparable listiterator
选项1:创建一个实现Comparable的列表,并在每次添加值时使用collections.sort(List l)对其进行排序.选项2:创建一个TreeSet(它始终保持自己的排序).
哪一个会更快?我问这个是因为List给了我ListIterator的选项,在我的情况下我需要它,因为它允许我在迭代时添加一个元素.
mer*_*ike 13
最重要的区别:
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
Run Code Online (Sandbox Code Playgroud)
要在迭代时插入元素而不获取a ConcurrentModificationException,您可以执行以下操作:
for (E e : new ArrayList<E>(collection)) {
// some other code
collection.add(anotherE);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5726 次 |
| 最近记录: |