目錄
一、Comparable
二、Comparator
Comparable和Comparator都表示對類型進行比較。但是Comparable表示的是某個類型本身具有比較的能力,而Comparator側重于類型本身無比較能力,但是我們可以通過外部定義其可以通過某種規則進行比較。
一、Comparable
Comparable是接口,位于java.lang包中。JDK中對Comparable的描述:
* This interface imposes a total ordering on the objects of each class that
* implements it. This ordering is referred to as the class's <i>natural
* ordering</i>, and the class's <tt>compareTo</tt> method is referred to as
* its <i>natural comparison method
即賦予實作該接口的類型本身具有比較能力。
該接口提供的主要方法:
public int compareTo(T o);
隻有一個入參,強調的是傳入的類型與this進行比較。
二、Comparator
Comparator也是接口,但是位于java.util包中,JDK對其描述如下;
* A comparison function, which imposes a <i>total ordering</i> on some
* collection of objects. Comparators can be passed to a sort method (such
* as {@link Collections#sort(List,Comparator) Collections.sort} or {@link
* Arrays#sort(Object[],Comparator) Arrays.sort}) to allow precise control
* over the sort order. Comparators can also be used to control the order of
* certain data structures (such as {@link SortedSet sorted sets} or {@link
* SortedMap sorted maps}), or to provide an ordering for collections of
* objects that don't have a {@link Comparable natural ordering}.
功能類似于Comparable,實作比較功能,但是更加側重于對未實作Comparale接口的類型,即本身沒有比較能力的 類型進行比較。
該接口提供的主要方法:
int compare(T o1, T o2);
有兩個入參,實作的是傳入的兩個對象的比較,而不要求這兩個對象本身具有比較能力。