Comparable & Comparator 都是用來(lái)實(shí)現(xiàn)集合中的排序的,只是 Comparable 是在集合內(nèi)部定義的方法實(shí)現(xiàn)的排序,
Comparator 是在集合外部實(shí)現(xiàn)的排序,所以,如想實(shí)現(xiàn)排序,就需要在集合外定義 Comparator 接口的方法或在集合內(nèi)實(shí)現(xiàn) Comparable 接口的方法。
Comparable 是一個(gè)對(duì)象本身就已經(jīng)支持自比較所需要實(shí)現(xiàn)的接口(如 String、Integer 自己就可以完成比較大小操作)
Comparator 是在集合外部實(shí)現(xiàn)的排序,所以,如想實(shí)現(xiàn)排序,就需要在集合外定義 Comparator 接口的方法或在集合內(nèi)實(shí)現(xiàn) Comparable 接口的方法。
Comparable 是一個(gè)對(duì)象本身就已經(jīng)支持自比較所需要實(shí)現(xiàn)的接口(如 String、Integer 自己就可以完成比較大小操作)
而 Comparator 是一個(gè)專(zhuān)用的比較器,當(dāng)這個(gè)對(duì)象不支持自比較或者自比較函數(shù)不能滿(mǎn)足你的要求時(shí),你可以寫(xiě)一個(gè)比較器來(lái)完成兩個(gè)對(duì)象之間大小的比較。
可以說(shuō)一個(gè)是自己完成比較,一個(gè)是外部程序?qū)崿F(xiàn)比較的差別而已。
用 Comparator 是策略模式(strategy design pattern),就是不改變對(duì)象自身,而用一個(gè)策略對(duì)象(strategy object)來(lái)改變它的行為。
比如:你想對(duì)整數(shù)采用絕對(duì)值大小來(lái)排序,Integer 是不符合要求的,你不需要去修改 Integer 類(lèi)(實(shí)際上你也不能這么做)去改變它的排序行為,只要使用一個(gè)實(shí)現(xiàn)了 Comparator 接口的對(duì)象來(lái)實(shí)現(xiàn)控制它的排序就行了。
Comparator 在java.util包中
Comparable 在java.lang包中
1
public class TestComparator {
2
AsComparator cl=new AsComparator();
3
/**
4
* @param args
5
*/
6
@SuppressWarnings("unchecked")
7
public static void main(String[] args) {
8
Integer[] datas=new Integer[20];
9
Random rand=new Random();
10
for(int i=0;i<20;i++){
11
datas[i]=new Integer(rand.nextInt(100));
12
}
13
Arrays.sort(datas);
14
System.out.println(Arrays.asList(datas));
15
TestComparator test=new TestComparator();
16
Arrays.sort(datas,test.cl);
17
System.out.println(Arrays.asList(datas));
18
19
}
20
21
@SuppressWarnings("rawtypes")
22
class AsComparator implements Comparator{
23
24
public int compare(Object o1, Object o2) {
25
int value1= Math.abs(((Integer)o1).intValue());
26
int value2=Math.abs(((Integer)o2).intValue());
27
return value1>value2?1:(value1==value2?0:-1);
28
}
29
30
}
31
32
33
}
34

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34
