Comparable 和 Comparator


相同點:

  Comparable<T> 和 Comparator<T>都是接口

不同點:

  兩者聲明的方法不同。前者是compareTo()方法,后者是compare()方法。

 

    Comparable<T>此接口是由具體某個有實際意義的類來實現,指示出此類的對象有什么樣的排序方法。下面的蘋果

public class Apple implements Comparable<Apple> {
    /**
     * 蘋果的重量
     */
    private int  weight;

    /**
     * 自然排序即從小到大
     * 返回1的,代表此對象比參數對象大,排在后面,這樣就可以控制降序或升序排列
     */
    @Override
    public int compareTo(Apple apple) {
        if (this.weight > apple.getWeight())
        {
            return -1;
        }
        else if (this.weight < apple.getWeight())
        {
            return 1;
        }
        else
        {
            return 0;
        }
    }
}

上面的例子中,蘋果重量輕的將排在后面,所以是降序排列。

 

    Comparator<T>此接口一般用來的定義比較器,不會由包含實際意義的類來實現,而是由具體比較器來實現。下面定義一個比較器:

public class WeightComparator implements Comparator<Apple> {
    /**
     * 蘋果的重量
     */
    private int  weight;

    /**
     * 自然排序即從小到大
     * 返回1的,代表此對象比參數對象大,排在前面,這樣就可以控制降序或升序排列
     */
    @Override
    public int compare(Apple a, Apple b) {
        if (a.getWeight() > b.getWeight())
        {
            return 1;
        }
        else if (a.getWeight() < b.getWeight())
        {
            return -1;
        }
        else
        {
            return 0;
        }
    }
    
    public static void main(String[] args)
    {
        Apple a = new Apple();
        Apple b = new Apple();
        Apple c = new Apple();
        a.setWeight(50);
        b.setWeight(150);
        c.setWeight(100);
        
        Apple[] apples = {a,b, c};
        Arrays.sort(apples, new WeightComparator());
        //50 100 150
        System.out.println("" + apples[0] + apples[1] + apples[2]);  
    }
}

上面的例子定義了一個重量比較器,我把它用來比較蘋果的重量,即使用泛型

public class WeightComparator implements Comparator<Apple>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM