Java - Collections.sort() performance

后端 未结 5 1384
孤街浪徒
孤街浪徒 2020-12-30 02:59

I\'m using Collections.sort() to sort a LinkedList whose elements implements Comparable interface, so they are sorted in a natural order. In the javadoc documentation its sa

5条回答
  •  长发绾君心
    2020-12-30 03:33

    If you say the list will be sorted "very frequent", you should consider holding the list in a sorted stated all the time, like using a tree instead of a LinkedList. Maybe you can even use some SortedSet instead of a List, if you don't have any duplicated values and don't need any List operations (as you are sorting them anyway all the time). Check the TreeSet class of the SortedSet implementation.

    This implementation provides guaranteed log(n) time cost for the basic operations (add, remove and contains).

    If you want to iterate over this "list" (which is actually a Set) you can use the Iterator of the class.

    Returns an iterator over the elements in this set in ascending order.

    If you have duplicate values inside the List you have to use some tricks (like putting the value in a new class which also got some delta for sorting equal object)

提交回复
热议问题