新接觸java沒多久,前幾天用到排序的問題,看到Comparator和Comparable兩個接口類有點迷惑,研究了兩天也沒理解有什么區(qū)別,今天在看《Java核心編程》時,才恍然大悟。在這里表達一下自己的想法。
當需要排序的集合或數(shù)組時可以使用Comparator或Comparable,它們都可以實現(xiàn)排序,但是它們的區(qū)別是Comparator從外部定義了對象的比較規(guī)則,而Comparable則是從內(nèi)部定義了對象是可比較的。下面將詳細解這句話。
一、 Comparator
Comparator從外部定義了對象的比較規(guī)則
比如,你要使用某人寫的一個矩形類Rect。現(xiàn)在你有一個Rect的集合(或數(shù)組),你想實現(xiàn)對Rect的排序,現(xiàn)在有一個問題,某人在實現(xiàn)Rect的時候沒有考慮到會有人將會比較Rect對象。這個時候你必須根據(jù)需要對Rect進行排序(比如,根據(jù)矩形的長進行排序),在這個場景下使用Comparator,因為Rect類已經(jīng)存在,你不能對其進行改變。
import java.util.*;
public class Rectangle {
public static void main(String[] args)
{
Rect[] rectArrays = new Rect[] {new Rect(3, 4), new Rect(5, 2), new Rect(4, 5)};
// 排序,將定義的RectComparator作為參數(shù)
Arrays.sort(rectArrays, new RectComparator());
for (int i=0; i != rectArrays.length; ++i)
System.out.println(rectArrays[i]);
}
// 定義一個Rect比較方式:根據(jù)Rect的長比較
public static class RectComparator implements Comparator<Rect>
{
public int compare(Rect o1, Rect o2)
{
return o1.getLength() - o2.getLength();
}
}
public static class Rect
{
Rect(int l, int w)
{
this.length = l;
this.width = w;
}
public int getLength()
{
return this.length;
}
public int getWidth()
{
return this.width;
}
public int getArea()
{
return this.length * this.width;
}
public String toString()
{
return "length: " + length + " width: " + width;
}
private int length;
private int width;
}
}
輸出:
length: 3 width: 4
length: 4 width: 5
length: 5 width: 2
二、 Comparable
Comparable則是從內(nèi)部定義了對象的是可比較的
還是以Rect為例,假如你是Rect的實現(xiàn)者,在你定義Rect時,你覺得有必要定義一個比較方式,這個時候就應(yīng)該使Rect繼承Comparable接口。如果你覺得較合理的排序方式是根據(jù)Rect的面積進行排序,那么可以這樣實現(xiàn)
import java.util.*;
public class Rectangle {
public static void main(String[] args)
{
Rect[] rectArrays = new Rect[] {new Rect(3, 4), new Rect(5, 2), new Rect(4, 5)};
Arrays.sort(rectArrays);
for (int i=0; i != rectArrays.length; ++i)
System.out.println(rectArrays[i]);
}
// 定義了Comparable接口
public static class Rect implements Comparable<Rect>
{
Rect(int l, int w)
{
this.length = l;
this.width = w;
}
public int getLength()
{
return this.length;
}
public int getWidth()
{
return this.width;
}
public int getArea()
{
return this.length * this.width;
}
public String toString()
{
return "length: " + length + " width: " + width;
}
// 重載compareTo函數(shù),按面積比較
@Override
public int compareTo(Rect that)
{
return this.getArea() - that.getArea();
}
private int length;
private int width;
}
}
輸出:
length: 5 width: 2
length: 3 width: 4
length: 4 width: 5
三、總結(jié)
通過Comparator和Comparable的意思我們也可以看出兩者的區(qū)別
Comparable意為“可比較的”,一個類繼承了Camparable接口則表明這個類的對象之間是可以相互比較的,這個類對象組成的集合就可以直接使用sort方法排序。
Comparator意為“比較算子”,因此Comparator可以看成一種算法的實現(xiàn),將算法和數(shù)據(jù)分離。
另外,通過定義方式,我們可以發(fā)現(xiàn)如果一個類繼承了Comparable接口,則表明這個類的對象之間是可以比較的,且比較的方式只有一種。但是Comparator可以定義多種比較方式。在第二個程序中,Rect定義了按面積進行比較,如果我們想按長對Rect進行排序,那么也可以通過Comparator來實現(xiàn)。
最后,再次強調(diào)
Comparator從外部定義了對象的比較規(guī)則,而Comparable則是從內(nèi)部定義了對象是可比較的。
參考資料
http://www.blogjava.net/fastunit/archive/2008/04/08/191533.html
《Java核心編程》第7版,p91-p92