這一介面會對實現了它的類施加一個整體的順序.這一順序被認為是類的自然順序,類的比較方法compareTo()也被認為是自然比較方法 實現這一介面的對象中,List類對象使用Collections.sort方法實現自動排序(升序),數組使用Arrays.sort()方法實現升序排序.實現這一介面的對象 ...
1 package java.lang; 2 import java.util.*;
1 /** 2 * This interface imposes a total ordering on the objects of each class that 3 * implements it. This ordering is referred to as the class's <i>natural 4 * ordering</i>, and the class's <tt>compareTo</tt> method is referred to as 5 * its <i>natural comparison method</i>.<p> 6 * 7 * Lists (and arrays) of objects that implement this interface can be sorted 8 * automatically by {@link Collections#sort(List) Collections.sort} (and 9 * {@link Arrays#sort(Object[]) Arrays.sort}). Objects that implement this 10 * interface can be used as keys in a {@linkplain SortedMap sorted map} or as 11 * elements in a {@linkplain SortedSet sorted set}, without the need to 12 * specify a {@linkplain Comparator comparator}.<p> 13 * 14 * The natural ordering for a class <tt>C</tt> is said to be <i>consistent 15 * with equals</i> if and only if <tt>e1.compareTo(e2) == 0</tt> has 16 * the same boolean value as <tt>e1.equals(e2)</tt> for every 17 * <tt>e1</tt> and <tt>e2</tt> of class <tt>C</tt>. Note that <tt>null</tt> 18 * is not an instance of any class, and <tt>e.compareTo(null)</tt> should 19 * throw a <tt>NullPointerException</tt> even though <tt>e.equals(null)</tt> 20 * returns <tt>false</tt>.<p> 21 * 22 * It is strongly recommended (though not required) that natural orderings be 23 * consistent with equals. This is so because sorted sets (and sorted maps) 24 * without explicit comparators behave "strangely" when they are used with 25 * elements (or keys) whose natural ordering is inconsistent with equals. In 26 * particular, such a sorted set (or sorted map) violates the general contract 27 * for set (or map), which is defined in terms of the <tt>equals</tt> 28 * method.<p> 29 * 30 * For example, if one adds two keys <tt>a</tt> and <tt>b</tt> such that 31 * {@code (!a.equals(b) && a.compareTo(b) == 0)} to a sorted 32 * set that does not use an explicit comparator, the second <tt>add</tt> 33 * operation returns false (and the size of the sorted set does not increase) 34 * because <tt>a</tt> and <tt>b</tt> are equivalent from the sorted set's 35 * perspective.<p> 36 * 37 * Virtually all Java core classes that implement <tt>Comparable</tt> have natural 38 * orderings that are consistent with equals. One exception is 39 * <tt>java.math.BigDecimal</tt>, whose natural ordering equates 40 * <tt>BigDecimal</tt> objects with equal values and different precisions 41 * (such as 4.0 and 4.00).<p> 42 * 43 * For the mathematically inclined, the <i>relation</i> that defines 44 * the natural ordering on a given class C is:<pre> 45 * {(x, y) such that x.compareTo(y) <= 0}. 46 * </pre> The <i>quotient</i> for this total order is: <pre> 47 * {(x, y) such that x.compareTo(y) == 0}. 48 * </pre> 49 * 50 * It follows immediately from the contract for <tt>compareTo</tt> that the 51 * quotient is an <i>equivalence relation</i> on <tt>C</tt>, and that the 52 * natural ordering is a <i>total order</i> on <tt>C</tt>. When we say that a 53 * class's natural ordering is <i>consistent with equals</i>, we mean that the 54 * quotient for the natural ordering is the equivalence relation defined by 55 * the class's {@link Object#equals(Object) equals(Object)} method:<pre> 56 * {(x, y) such that x.equals(y)}. </pre><p> 57 * 58 * This interface is a member of the 59 * <a href="{@docRoot}/../technotes/guides/collections/index.html"> 60 * Java Collections Framework</a>. 61 * 62 * @param <T> the type of objects that this object may be compared to 63 * 64 * @author Josh Bloch 65 * @see java.util.Comparator 66 * @since 1.2 67 */
這一介面會對實現了它的類施加一個整體的順序.這一順序被認為是類的自然順序,類的比較方法compareTo()也被認為是自然比較方法
實現這一介面的對象中,List類對象使用Collections.sort方法實現自動排序(升序),數組使用Arrays.sort()方法實現升序排序.實現這一介面的對象在有序Map中被用來作為Key進行排序的;在有序Set中,是作為set集合中的元素排序的.而使用這些方法時,我們並不需要指定比較器comparator
對於類C的任意變數e1和e2,當且僅當e1.compareTo(e2) == 0的和e1.equals(e2)有相同的返回值時,類的自然排序才能被認為是和equals方法的 結果保持一致的.
註意:雖然e.equals(null)返回值為false,但是null不是任何類的實例,所以如果調用方法e.compareTo(null)應該拋出異常NullPointerException
我們強烈建議(儘管並不是必須的):自然排序應該和equals結果保持一致(這是因為自然排序用到了compare方法,這裡的意思是需要滿足關係: e1.compareTo(e2) == 0的和e1.equals(e2)有相同的返回值).這是因為沒有明確比較器的有序set(和有序map) (什麼叫沒有明確比較器?對於TreeSet和TreeMap,都有多個實例構造函數,而其中有一個無參構造函數,就指定了比較器comparator = null;同時, 這也說明瞭,如果你想在建立有序set或者有序map時就指定它的排序方法,那麼可以給構造函數傳入一個比較器參數即可.),如果自然排序不能和equals方法 保持一致,那麼它們會表現出一些詭異的行為.而且,這樣的有序set(或者map)和equals中通用規範是矛盾的。
舉個例子:如果向一個沒有明確比較器的有序set中添加2個值a和b(a.equals(b)值為false,而 a.compareTo(b) == 0 值為true(a==b)), 那麼第二次的add操作會失敗,因為從有序set的角度看,a和b是等值的.
實質上,所有實現了Comparable介面的java核心類,都滿足自然排序的要求.唯一的例外類是:BigDecimal類.它的自然排序要求是:值相等而精度是不等的. 所以,精度不同但值相同的兩個BigDecimal對象,它們的equals方法返回值應該為true,而compare()方法應該返回0:
類C上面的等價關係,自然排序是對類C上面的元素整體的一個排序,這符合compareTo的通用規範. 當我們說一個類的自然排序是和equals結果保持一致.那就意味著自然排序是由這個類的equals方法定義的等價關係.
1 public interface Comparable<T> { 2 /** 3 * Compares this object with the specified object for order. Returns a 4 * negative integer, zero, or a positive integer as this object is less 5 * than, equal to, or greater than the specified object. 6 * 7 * <p>The implementor must ensure <tt>sgn(x.compareTo(y)) == 8 * -sgn(y.compareTo(x))</tt> for all <tt>x</tt> and <tt>y</tt>. (This 9 * implies that <tt>x.compareTo(y)</tt> must throw an exception iff 10 * <tt>y.compareTo(x)</tt> throws an exception.) 11 * 12 * <p>The implementor must also ensure that the relation is transitive: 13 * <tt>(x.compareTo(y)>0 && y.compareTo(z)>0)</tt> implies 14 * <tt>x.compareTo(z)>0</tt>. 15 * 16 * <p>Finally, the implementor must ensure that <tt>x.compareTo(y)==0</tt> 17 * implies that <tt>sgn(x.compareTo(z)) == sgn(y.compareTo(z))</tt>, for 18 * all <tt>z</tt>. 19 * 20 * <p>It is strongly recommended, but <i>not</i> strictly required that 21 * <tt>(x.compareTo(y)==0) == (x.equals(y))</tt>. Generally speaking, any 22 * class that implements the <tt>Comparable</tt> interface and violates 23 * this condition should clearly indicate this fact. The recommended 24 * language is "Note: this class has a natural ordering that is 25 * inconsistent with equals." 26 * 27 * <p>In the foregoing description, the notation 28 * <tt>sgn(</tt><i>expression</i><tt>)</tt> designates the mathematical 29 * <i>signum</i> function, which is defined to return one of <tt>-1</tt>, 30 * <tt>0</tt>, or <tt>1</tt> according to whether the value of 31 * <i>expression</i> is negative, zero or positive. 32 * 33 * @param o the object to be compared. 34 * @return a negative integer, zero, or a positive integer as this object 35 * is less than, equal to, or greater than the specified object. 36 * 37 * @throws NullPointerException if the specified object is null 38 * @throws ClassCastException if the specified object's type prevents it 39 * from being compared to this object. 40 */ 41 public int compareTo(T o); 42 }
將當前對象a和指定對象b進行比較.
a>b:返回正數;
a=b:返回0;
a<b:返回負數;
實現這一介面的類必須保證對於任意的x和y,都應該滿足的條件是:sgn(x.compareTo(y)) == -sgn(y.compareTo(x)) 這意味如果y.compareTo(x)拋出異常,則x.compareTo(y)必須拋出異常.
實現這個介面的類還必須保證:聯繫是具有傳遞性的: 如果: x.compareTo(y)>=0 && y.compareTo(z)>=0成立,則:x.compareTo(z)>=0也成立.
最後,實現這個的類必須保證:對於任意的z,如果x.compareTo(y)==0成立,則sgn(x.compareTo(z)) == sgn(y.compareTo(z))也成立.
我們強烈建議,但並非嚴格約定:x.compareTo(y)==0和x.equals(y)的返回值一致. 通常,任何實現了Comparable介面但違反了這一條件的類應該明確的表明這一事實. 作為這一事實的提醒語言,它可以這樣寫: 註意:這個類的自然排序並沒有和equals結果保持一致.
在前面的表述中,用到的符號sgn是數學函數signum的一種表達式,它定義了:
sgn的參數為負數,返回-1;
sgn的參數為正數,返回1;
sgn的參數為0,返回0.