选项 1:创建一个实现 Comparable 的列表,并在每次添加值时使用 collections.sort(List l) 对它进行排序。
选项 2:创建一个 TreeSet(它始终保持排序)。
哪一个会更快?我问这个是因为 List 为我提供了在我的情况下需要的 ListIterator 选项,因为它允许我在迭代时添加元素。
最重要的区别:
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
, 你可以做:
for (E e : new ArrayList<E>(collection)) {
// some other code
collection.add(anotherE);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)