1. 程式人生 > >(The difference between Comparator and Comparable)Comparator和Comparable的區別

(The difference between Comparator and Comparable)Comparator和Comparable的區別

來源於 https://blog.csdn.net/zhushuai1221/article/details/51760663

in view of https://blog.csdn.net/zhushuai1221/article/details/51760663

原始碼(source code)

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

public interface Comparator<T>{
    int compare(T o1,T o2);
    boolean equals(Object obj);
}

1.Comparable是一個物件本身就已經支援比較,比如String,Integer都有自己的comparTo方法
2.Comparator是一個專用的比較器,當物件不支援自己比較或自比較函式不能滿足要求時.
可以寫一個比較器來完成兩個物件之間大小的比較,Comparator體現了一種策略模式,
就是不改變物件自己,而用一個策略物件來改變它的行為.
1.Comparable is an object itself that already supports comparison,for example, String and Integer have their own comparTo methods.
2.Comparator is a special-purpose comparator,when the object does not support its own comparison or
self comparison function.We can use a special class that implements comparator,and provide @Override methods for the comparison between object (o1) and object (o2).In another hand,Comparator
reflects a kind of stragety pattern instead of changing the object itself,it uses a policy object to change it’s behavior;

第一種形式,使用Comparable來進行比較.(The first way, use Comparable for comparison)

class A implements Comparable<A>{
    public int i;
    public A(int i){  //預設建構函式
        this.i = i;
    }

    @Override
    public int compareTo(A o) {  //實現從小到大排序.
        return (i == o.i)
                ? 0 : (i > o.i)
                ? 1 : -1;
    }
}

public class TestComp{
    public static void main(String[] args) {
        A a = new A(1);
        A b = new A(2);
        A d = new A(4);
        A c = new A(3);
        A [] aa = new A[]{a,b,d,c};
        Arrays.sort(aa);  //這裡呼叫的是Arrays.sort 會自動根據comparTo來進行比較.
        
        for (int i = 0; i < aa.length; i++) {  //列印輸出陣列.
            System.out.println(aa[i].i);
        }
    }
}

第二種形式,使用Comparator來進行比較(The second way,use Comparator for comparison )

class B{
    int i;
    public B(int i){ //預設建構函式
        this.i = i;
    }
}

class ComparatorB implements Comparator<B>{

    @Override
    public int compare(B o1, B o2) {
        return (o1.i == o2.i)
                ? 0 : (o1.i > o2.i)
                ? 1 : -1;
    }
}

public class TestComp{
    public static void main(String[] args) {
     B c = new B(3);
     B d = new B(4);
     B a = new B(1);
     B b = new B(2);

     B[] bb = new B[]{c,d,a,b};
     Arrays.sort(bb,new ComparatorB());
     for (B b1:bb) {
         System.out.println(b1.i);
     }
   }
}