天天看點

Java比較器-Comparable和Comparator

Comparable

This interface imposes a total ordering on the objects of each class that implements it. This ordering is referred to as the class’s natural ordering, and the class’s compareTo method is referred to as its natural comparison method.

Lists (and arrays) of objects that implement this interface can be sorted automatically by Collections.sort (and Arrays.sort). Objects that implement this interface can be used as keys in a sorted map or as elements in a sorted set, without the need to specify a comparator.

接口定義:

public interface Comparable<T> {
    public int compareTo(T o);
}
           

  Comparable接口位于java.lang包下,Comparable相當于内部比較器。實作該接口的類為支援排序的,實作該接口的對象的List(或Array)可通過Collection.sort(或Arrays.sort)排序。此外,實作該接口的對象可以作為sorted map的鍵或sorted set中的元。使用範例如下:

public class Cat implements Comparable{

    private int age;

    private String name;

    Cat(int age, String name) {
        this.age = age;
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    // 不指定Comparable範型類型時,比較對象為Object
    @Override
    public int compareTo(Object o) {
        return this.age - ((Cat)o).age;
    }

    @Override
    public String toString() {
        return "Cat{" +
                "age=" + age +
                ", name='" + name + '\'' +
                '}';
    }

    public static void main(String[] args) {
        Cat cat1 = new Cat(, "XXXX");
        Cat cat2 = new Cat(, "YYYY");
        Cat cat3 = new Cat(, "ZZZZ");

        List<Cat> cats = new ArrayList<Cat>();
        cats.add(cat1);
        cats.add(cat2);
        cats.add(cat3);

        Collections.sort(cats);

        for(Cat cat : cats) {
            System.out.println(cat);
        }
    }

}
           

  類Cat不實作Comparable接口時,Collection.sort方法不可用,會提示Cat類實作該接口。實作Comparable接口時可以指定範型類型,也可以不指定,指定具體範型類型時compareTo方法的參數為範型類型,不指定時預設為Object。

Comparator

A comparison function, which imposes a total ordering on some collection of objects. Comparators can be passed to a sort method (such as Collections.sort or Arrays.sort) to allow precise control over the sort order. Comparators can also be used to control the order of certain data structures (such as sorted sets or sorted maps), or to provide an ordering for collections of objects that don’t have a natural ordering.

接口定義:

public interface Comparator<T> {

    int compare(T o1, T o2);
    boolean equals(Object obj);

    ...
}
           

  Comparator接口位于java.util包下,Comparator相當于外部比較器。一個類除了實作Comparable方法,讓自己具有排序功能外,也可以通過外部定義比較器Comparator,傳遞給Collections.sort(或 Arrays.sort)等方法實作排序。同樣,實作Comparator接口可不指定具體範型類型,這時預設比較類行為Object。說明:實作Comparator接口的對象必須實作compare方法,但可以不實作equals方法,因為Object類中預設實作了equals方法。

使用範例:

public class Cat {

    private int age;

    private String name;

    Cat(int age, String name) {
        this.age = age;
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Cat{" +
                "age=" + age +
                ", name='" + name + '\'' +
                '}';
    }

    public static void main(String[] args) {
        Cat cat1 = new Cat(, "XXXX");
        Cat cat2 = new Cat(, "YYYY");
        Cat cat3 = new Cat(, "ZZZZ");

        List<Cat> cats = new ArrayList<Cat>();
        cats.add(cat1);
        cats.add(cat2);
        cats.add(cat3);

         // 也可單獨定義實作Comparator接口的比較類
        Collections.sort(cats, new Comparator<Cat>() {
            @Override
            public int compare(Cat o1, Cat o2) {
                return o1.age - o2.age;  // 降序:return o2.age - o1.age;
            }
        });

        for(Cat cat : cats) {
            System.out.println(cat);
        }
    }
}