Java – using the comparable vs TreeSet list

Option 1: create a list that implements comparable and use collections. Net each time you add a value Sort (List L) sorts them

Which one will be faster? I ask this because list gives me the option of listiterator. In my case, I need it because it allows me to add an element during iteration

Solution

The most important difference:

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@H_403_10@ 
 

要在迭代时插入元素而不获取ConcurrentModificationException,您可以执行以下操作:

for (E e : new ArrayList<E>(collection)) {
    // some other code

    collection.add(anotherE);
}@H_403_10@
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>