Comparable & Comparator 都是用來(lái)實(shí)現集合中元素的比較、排序的,只是 Comparable 是在集合內部定義的方法實(shí)現的排序,Comparator 是在集合外部實(shí)現的排序,所以,如想實(shí)現排序,就需要在集合外定義 Comparator 接口的方法或在集合內實(shí)現 Comparable 接口的方法。
Comparator位于包java.util下,而Comparable位于包 java.lang下
Comparable 是一個(gè)對象本身就已經(jīng)支持自比較所需要實(shí)現的接口(如 String、Integer 自己就可以完成比較大小操作,已經(jīng)實(shí)現了Comparable接口)
自定義的類(lèi)要在加入list容器中后能夠排序,可以實(shí)現Comparable接口,在用Collections類(lèi)的sort方法排序時(shí),如果不指定Comparator,那么就以自然順序排序,如API所說(shuō):
Sorts the specified list into ascending order, according to the natural ordering of its elements. All elements in the list must implement the Comparable interface
這里的自然順序就是實(shí)現Comparable接口設定的排序方式。
而 Comparator 是一個(gè)專(zhuān)用的比較器,當這個(gè)對象不支持自比較或者自比較函數不能滿(mǎn)足你的要求時(shí),你可以寫(xiě)一個(gè)比較器來(lái)完成兩個(gè)對象之間大小的比較。
可以說(shuō)一個(gè)是自已完成比較,一個(gè)是外部程序實(shí)現比較的差別而已。
用 Comparator 是策略模式(strategy design pattern),就是不改變對象自身,而用一個(gè)策略對象(strategy object)來(lái)改變它的行為。
比如:你想對整數采用絕對值大小來(lái)排序,Integer 是不符合要求的,你不需要去修改 Integer 類(lèi)(實(shí)際上你也不能這么做)去改變它的排序行為,只要使用一個(gè)實(shí)現了 Comparator 接口的對象來(lái)實(shí)現控制它的排序就行了。
// AbsComparator.java
import java.util.*;
public class AbsComparator implements Comparator {
public int compare(Object o1, Object o2) {
int v1 = Math.abs(((Integer)o1).intValue());
int v2 = Math.abs(((Integer)o2).intValue());
return v1 > v2 ? 1 : (v1 == v2 ? 0 : -1);
}
}
可以用下面這個(gè)類(lèi)測試 AbsComparator:
// Test.java
import java.util.*;
public class Test {
public static void main(String[] args) {
//產(chǎn)生一個(gè)20個(gè)隨機整數的數組(有正有負)
Random rnd = new Random();
Integer[] integers = new Integer[20];
for(int i = 0; i < integers.length; i++)
integers[i] = new Integer(rnd.nextInt(100) * (rnd.nextBoolean() ? 1 : -1));
System.out.println("用Integer內置方法排序:");
Arrays.sort(integers);
System.out.println(Arrays.asList(integers));
System.out.println("用AbsComparator排序:");
Arrays.sort(integers, new AbsComparator());
System.out.println(Arrays.asList(integers));
}
}
Collections.sort((List<T> list, Comparator<? super T> c)是用來(lái)對list排序的。
如果不是調用sort方法,相要直接比較兩個(gè)對象的大小,如下:
Comparator定義了倆個(gè)方法,分別是 int compare(T o1, T o2)和 boolean equals(Object obj),
用于比較兩個(gè)Comparator是否相等
true only if the specified object is also a comparator and it imposes the same ordering as this comparator.
有時(shí)在實(shí)現Comparator接口時(shí),并沒(méi)有實(shí)現equals方法,可程序并沒(méi)有報錯,原因是實(shí)現該接口的類(lèi)也是Object類(lèi)的子類(lèi),而Object類(lèi)已經(jīng)實(shí)現了equals方法
Comparable接口只提供了 int compareTo(T o)方法,也就是說(shuō)假如我定義了一個(gè)Person類(lèi),這個(gè)類(lèi)實(shí)現了 Comparable接口,那么當我實(shí)例化Person類(lèi)的person1后,我想比較person1和一個(gè)現有的Person對象person2的大小時(shí),我就可以這樣來(lái)調用:person1.comparTo(person2),通過(guò)返回值就可以判斷了;而此時(shí)如果你定義了一個(gè) PersonComparator(實(shí)現了Comparator接口)的話(huà),那你就可以這樣:PersonComparator comparator= new PersonComparator();
comparator.compare(person1,person2);。
本站僅提供存儲服務(wù),所有內容均由用戶(hù)發(fā)布,如發(fā)現有害或侵權內容,請
點(diǎn)擊舉報。