用Collections進行大小排序

  1.Collections

Collections和Collection的區別:

Collections是java.utils下面的類,含有許多集合的相關操作的靜態方法

Collections是java.utils下面的接口,是許多集合的上級接口

  2.Collections的sort方法

sort方法用於對數據集合進行大小排序


/**
 * 使用給定的比較器對給定的列表進行排序。該算法穩定意味着相等的元素沒有得到重新排序。
 *
 * @throws ClassCastException if any element does not implement {@code Comparable},
 *     or if {@code compareTo} throws for any pair of elements.
 */
@SuppressWarnings("unchecked")
public static <T> void sort(List<T> list, Comparator<? super T> comparator) {
    if (list.getClass() == ArrayList.class) {
        ArrayList<T> arrayList = (ArrayList<T>) list;
        T[] array = (T[]) arrayList.array;
        int end = arrayList.size();
        Arrays.sort(array, 0, end, comparator);
        arrayList.modCount++;
    } else {
        T[] array = list.toArray((T[]) new Object[list.size()]);
        Arrays.sort(array, comparator);
        int i = 0;
        ListIterator<T> it = list.listIterator();
        while (it.hasNext()) {
            it.next();
            it.set(array[i++]);
        }
    }
}


第一個參數爲要排序的數據集,例如ArrayList<String> mDatas = new ArrayList<String>();

第二個參數爲Comparator,它爲一個抽象接口,這裏我們new一個此類對象


Comparator comparator = new Comparator<String>() {

			@Override
			public int compare(String lhs, String rhs) {
				// compareToIgnoreCase:進行比較,忽略大小寫
				// 如果參數字符串等於此字符串,則返回 0 值;如果按字典順序此字符串小於字符串參數,則返回一個小於 0
				// 的值;如果按字典順序此字符串大於字符串參數,則返回一個大於 0 的值。
				return lhs.compareToIgnoreCase(rhs);
			}
		};




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