自然(可比較)與顯式(比較)排序

有兩種 Collections.sort() 方法:

  • List<T> 作為引數,其中 T 必須實現 Comparable 並覆蓋確定排序順序的 compareTo() 方法。
  • 將 List 和 Comparator 作為引數的一種方法,比較器確定排序順序。

首先,這是一個實現 Comparable 的 Person 類:

public class Person implements Comparable<Person> {         
    private String name;  
    private int age;

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }         

    @Override
    public int compareTo(Person o) {
        return this.getAge() - o.getAge();
    }
    @Override
    public String toString() {
        return this.getAge()+"-"+this.getName();
    }

}

以下是如何使用上面的類按照 compareTo() 方法重寫定義的元素的自然順序對 List 進行排序:

//-- usage
List<Person> pList = new ArrayList<Person>();
            Person p = new Person();
            p.setName("A");
            p.setAge(10);
            pList.add(p);
            p = new Person();
            p.setName("Z");
            p.setAge(20);
            pList.add(p);
            p = new Person();
            p.setName("D");
            p.setAge(30);
            pList.add(p);
            
            //-- natural sorting i.e comes with object implementation, by age
            Collections.sort(pList);

            System.out.println(pList);

以下是如何使用匿名內聯比較器對未實現 Comparable 的 List 進行排序,或者在這種情況下,按照自然排序以外的順序對 List 進行排序:

            //-- explicit sorting, define sort on another property here goes with name
            Collections.sort(pList, new Comparator<Person>() {

                @Override
                public int compare(Person o1, Person o2) {
                    return o1.getName().compareTo(o2.getName());
                }
            });            
            System.out.println(pList);