ArrayList排序

今天遇到ArrayList排序,說起來真是汗,居然不知道,基礎是夠差,網上查閱一番。發現用到接口Comparator(定義排序規則,即ArrayList裏面的對象應該按什麼規則排序),可以自己用類實現這個接口,實現compare接口,這個接口返回值即爲你的規則。升序降序都可以自己來定,然後OK了,只要用集合類Collections的sort方法就可以了。sort有兩個參數,第一個參數是你的比較規則類,第二個則是你的List。方便啊。
惡補基礎
======================================================================

sort
public static <T> void sort(List<T> list,
Comparator<? super T> c)
Sorts the specified list according to the order induced by the specified comparator. All elements in the list must be mutually comparable using the specified comparator (that is, c.compare(e1, e2) must not throw a ClassCastException for any elements e1 and e2 in the list).
This sort is guaranteed to be stable: equal elements will not be reordered as a result of the sort.

The sorting algorithm is a modified mergesort (in which the merge is omitted if the highest element in the low sublist is less than the lowest element in the high sublist). This algorithm offers guaranteed n log(n) performance. The specified list must be modifiable, but need not be resizable. This implementation dumps the specified list into an array, sorts the array, and iterates over the list resetting each element from the corresponding position in the array. This avoids the n2 log(n) performance that would result from attempting to sort a linked list in place.


Parameters:
list - the list to be sorted.
c - the comparator to determine the order of the list. A null value indicates that the elements' natural ordering should be used.
Throws:
ClassCastException - if the list contains elements that are not mutually comparable using the specified comparator.
UnsupportedOperationException - if the specified list's list-iterator does not support the set operation.
See Also:
Comparator


======================================================================
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章