List with Comparable Vs TreeSet

人盡茶涼 提交于 2019-12-03 14:20:09

The most important differences:

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

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);
}

Collections.sort uses a modified merge-sort with nlog(n) sort time. If you call the method on every addition you might end up with n^2log(n) time. Whereas insertion in TreeSet is guaranteed log(n). So if you call it on every addition it becomes n.log(n). So I would suggest using TreeSet instead. But TreeSet doesn't allow duplicates, so that might affect your decision.

If you are using List, then instead of using Collections.sort, there is one thing you can do to optimize; as you know that each time you insert the element in the list, the list is already sorted, so using insertion sort here will give you a better performance, as insertion sort performs better in such cases.

Use TreeSet here.

Adding to TreeSet is a log(n) operation. Adding to list is const time, but sorting it is n log(n).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!