欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Comparable接口源码分析

程序员文章站 2022-06-30 18:51:40
这一接口会对实现了它的类施加一个整体的顺序.这一顺序被认为是类的自然顺序,类的比较方法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) &lt;= 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)&gt;0 &amp;&amp; y.compareTo(z)&gt;0)</tt> implies
14      * <tt>x.compareTo(z)&gt;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.