Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List with Comparable Vs 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).

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.

like image 272
aps Avatar asked Aug 07 '11 06:08

aps


2 Answers

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);
}
like image 85
meriton Avatar answered Sep 28 '22 10:09

meriton


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.

like image 42
Suraj Chandran Avatar answered Sep 28 '22 09:09

Suraj Chandran