直接上代碼:
import java.util.ArrayList;import java.util.Collections;import java.util.Comparator;import java.util.List;/** * * <p> * ClassName CollectionsSort * </p> * <p> * Description 主要介紹兩種集合的排序演算法<br/> * 第一:java.util.Collections.sort(java.util.List),要求所排序元素必須實現java.lang.Comparable介面 <br/> * 第二:java.util.Collections.sort(java.util.List, java.util.Comparator),這個方法要求實現java.util.Comparator介面 <br/> * 第三:下面的例子使用的是對int型屬性排序,對String屬性排序可以使用以下方法<br/> * public int compareTo(Cat o){return this.getName().compareTo(o.getName(0);}<br/> * 第四:compareTo()函數的說明 <br/> * 如果 結果;<br/> * <0 a<b ;<br/>= * ==0 a==b;<br/> * >=0 a>b; * </p> * * @author wangxu wangx89@126.com * <p> * Date 2014-9-16 下午04:52:57 * </p> * @version V1.0 * */public class CollectionsSort {public static void main(String[] args) {// method1();測試第一個方法method2();// 測試第二個方法}public static void method1() {List<Cat> list = new ArrayList<Cat>();Cat c = new Cat("a", 10);list.add(c);c = new Cat("b", 20);list.add(c);c = new Cat("c", 3);list.add(c);// 升序排列輸出Collections.sort(list);System.out.println(list);// 降序排列輸出Collections.sort(list, Collections.reverseOrder());System.out.println(list);}public static void method2() {List<Cat> list = new ArrayList<Cat>();Cat c = new Cat("a", 10);list.add(c);c = new Cat("b", 20);list.add(c);c = new Cat("c", 3);list.add(c);Comparator<Cat> catComparator = new Cat();// 升序排列輸出Collections.sort(list, catComparator);System.out.println(list);// 降序排列輸出catComparator = Collections.reverseOrder(catComparator);Collections.sort(list, catComparator);System.out.println(list);}}class Cat implements Comparable<Cat>, Comparator<Cat> {private int age;private String name;public Cat() {}public Cat(String name, int age) {this.age = age;this.name = name;}public int getAge() {return this.age;}public String getName() {return this.name;}public void setAge(int age) {this.age = age;}public void setName(String name) {this.name = name;}// 實現了Comparable介面,不要重寫該方法@Overridepublic int compareTo(Cat o) {// TODO Auto-generated method stubreturn this.age - o.age;}@Overridepublic String toString() {// TODO Auto-generated method stubreturn "名字:" + getName() + ",年齡:" + getAge();}// 實現了Comparator介面,需要重寫該方法@Overridepublic int compare(Cat o1, Cat o2) {// TODO Auto-generated method stubreturn o1.getAge() - o2.getAge();}}