Java基礎[6]-3-接口Comparator和Comparable

Comparable & Comparator 都是用來實現集合中元素的比較、排序的。

  • Comparator位於包 java.util, Comparable位於包 java.lang .

  • Comparator 是在集合外部實現的排序, Comparable 是在集合內部定義的方法實現的排序.

  • 實現Comparator需要覆蓋 compare 方法,compare方法裏面實現比較。
    實現Comparable接口要覆蓋compareTo方法, 在compareTo方法裏面實現比較。

  • Comparable 只要實現Comparable 接口的對象直接就成爲一個可以比較的對象, 但是需要修改源代碼。
    Comparator 的好處是不需要修改源代碼, 而是另外實現一個比較器, 當某個自定義的對象需要作比較的時候,把比較器和對象一起傳遞過去就可以比大小了。可以根據需求,靈活的指定元素的排序規則。戶可以自己實現複雜的可以通用的邏輯,使其可以匹配一些比較簡單的對象,那樣就可以節省很多重複勞動了。

備註:
1.java常見類如String , Integer等都已實現Comparable 接口,都有自己獨特的排序規則.
2.元素自身所具有的排序規則稱爲:自然排序


示例代碼

Apple類–實現Comparable接口

/**
 * 實現Comparable接口
 * 類的對象擁有比較特性,
 * 在類的內部實現compareTo()方法
 * @author gao tianci
 * @version $Id: Apple.java, v 0.1 2017年7月22日 下午6:37:34 gao tianci Exp $
 */
public class Apple implements Comparable<Apple>, Serializable {
    /**  */
    private static final long serialVersionUID = 7844213446947863973L;
    private String            name;
    private Double            price;

    public Apple(String name, Double price) {
        super();
        this.name = name;
        this.price = price;
    }

    /** 
     * 先按名字排序,名字相同按價格排序
     * @see java.lang.Comparable#compareTo(java.lang.Object)
     */
    @Override
    public int compareTo(Apple otherApple) {

        int flag = name.compareTo(otherApple.name);
        //名字相同,比價格
        if (flag == 0) {
            //Double類型自身實現Comparable接口
            return price.compareTo(otherApple.price);
        }
        return flag;
    }

    @Override
    public String toString() {
        return "Apple [name=" + name + ", price=" + price + "]";
    }
}

Egg 類

/**
 * @author gao tianci
 * @version $Id: Egg.java, v 0.1 2017年7月22日 下午6:58:25 gao tianci Exp $
 */
public class Egg implements Serializable {

    /**  */
    private static final long serialVersionUID = 5635366463709253737L;

    private String            name;
    private Double            price;

    public Egg(String name, Double price) {
        super();
        this.name = name;
        this.price = price;
    }

    public String getName() {
        return name;
    }

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

    public Double getPrice() {
        return price;
    }

    public void setPrice(Double price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "Egg [name=" + name + ", price=" + price + "]";
    }
}

EggComparator –比較器, 實現Comparator接口

/**
 * 實現Comparator接口,
 * 在類的外部實現一個與類相關的比較器,
 * 實現compare()方法,
 * 可以對一個類從不同的維度實現多個比較器,
 * 控制更加靈活
 * 
 * @author gao tianci
 * @version $Id: EggComparator.java, v 0.1 2017年7月22日 下午6:58:17 gao tianci Exp $
 */
public class EggComparator implements Comparator<Egg> {

    /** 
     *  先按名字排序,名字相同按價格排序
     * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
     */
    @Override
    public int compare(Egg one, Egg another) {
        int flag = one.getName().compareTo(another.getName());
        //名字相同比價格
        if (flag == 0) {
            return one.getPrice().compareTo(another.getPrice());
        }
        return flag;
    }
}

測試類


/**
 * @author gao tianci
 * @version $Id: TestCase.java, v 0.1 2017年7月22日 下午7:17:51 gao tianci Exp $
 */
public class TestCase {
    @Test
    public void test() {
        ArrayList<Apple> list = new ArrayList<>();
        list.add(new Apple("apple", 3.0));
        list.add(new Apple("apple", 2.0));
        list.add(new Apple("apple", 1.0));
        list.add(new Apple("apple1", 2.0));
        list.add(new Apple("apple1", 1.0));

        System.out.println("----排序前----");
        list.forEach((item) -> System.out.println(item + ";"));
        //排序
        Collections.sort(list);
        System.out.println("----排序後----");
        list.forEach((item) -> System.out.println(item + ";"));

        System.out.println("================");
        ArrayList<Egg> arrays = new ArrayList<>();
        arrays.add(new Egg("egg1", 3.0));
        arrays.add(new Egg("egg1", 2.0));
        arrays.add(new Egg("egg1", 1.0));
        arrays.add(new Egg("egg", 2.0));
        arrays.add(new Egg("egg", 1.0));

        System.out.println("----排序前----");
        arrays.forEach((item) -> System.out.println(item + ";"));
        //排序,比較器作爲入參
        Collections.sort(arrays, new EggComparator());
        System.out.println("----排序後----");
        arrays.forEach((item) -> System.out.println(item + ";"));
    }
}

測試結果

----排序前----
Apple [name=apple, price=3.0];
Apple [name=apple, price=2.0];
Apple [name=apple, price=1.0];
Apple [name=apple1, price=2.0];
Apple [name=apple1, price=1.0];
----排序後----
Apple [name=apple, price=1.0];
Apple [name=apple, price=2.0];
Apple [name=apple, price=3.0];
Apple [name=apple1, price=1.0];
Apple [name=apple1, price=2.0];
================
----排序前----
Egg [name=egg1, price=3.0];
Egg [name=egg1, price=2.0];
Egg [name=egg1, price=1.0];
Egg [name=egg, price=2.0];
Egg [name=egg, price=1.0];
----排序後----
Egg [name=egg, price=1.0];
Egg [name=egg, price=2.0];
Egg [name=egg1, price=1.0];
Egg [name=egg1, price=2.0];
Egg [name=egg1, price=3.0];
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章