jdk源码阅读之Comparable接口区别于Comparator

附上源码

/**
 * 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</i>.<p>
 *
 * Lists (and arrays) of objects that implement this interface can be sorted
 * automatically by {@link Collections#sort(List) Collections.sort} (and
 * {@link Arrays#sort(Object[]) Arrays.sort}).  Objects that implement this
 * interface can be used as keys in a {@linkplain SortedMap sorted map} or as
 * elements in a {@linkplain SortedSet sorted set}, without the need to
 * specify a {@linkplain Comparator comparator}.<p>
 *
 * The natural ordering for a class <tt>C</tt> is said to be <i>consistent
 * with equals</i> if and only if <tt>e1.compareTo(e2) == 0</tt> has
 * the same boolean value as <tt>e1.equals(e2)</tt> for every
 * <tt>e1</tt> and <tt>e2</tt> of class <tt>C</tt>.  Note that <tt>null</tt>
 * is not an instance of any class, and <tt>e.compareTo(null)</tt> should
 * throw a <tt>NullPointerException</tt> even though <tt>e.equals(null)</tt>
 * returns <tt>false</tt>.<p>
 *
 * It is strongly recommended (though not required) that natural orderings be
 * consistent with equals.  This is so because sorted sets (and sorted maps)
 * without explicit comparators behave "strangely" when they are used with
 * elements (or keys) whose natural ordering is inconsistent with equals.  In
 * particular, such a sorted set (or sorted map) violates the general contract
 * for set (or map), which is defined in terms of the <tt>equals</tt>
 * method.<p>
 *
 * For example, if one adds two keys <tt>a</tt> and <tt>b</tt> such that
 * {@code (!a.equals(b) && a.compareTo(b) == 0)} to a sorted
 * set that does not use an explicit comparator, the second <tt>add</tt>
 * operation returns false (and the size of the sorted set does not increase)
 * because <tt>a</tt> and <tt>b</tt> are equivalent from the sorted set's
 * perspective.<p>
 *
 * Virtually all Java core classes that implement <tt>Comparable</tt> have natural
 * orderings that are consistent with equals.  One exception is
 * <tt>java.math.BigDecimal</tt>, whose natural ordering equates
 * <tt>BigDecimal</tt> objects with equal values and different precisions
 * (such as 4.0 and 4.00).<p>
 *
 * For the mathematically inclined, the <i>relation</i> that defines
 * the natural ordering on a given class C is:<pre>
 *       {(x, y) such that x.compareTo(y) &lt;= 0}.
 * </pre> The <i>quotient</i> for this total order is: <pre>
 *       {(x, y) such that x.compareTo(y) == 0}.
 * </pre>
 *
 * It follows immediately from the contract for <tt>compareTo</tt> that the
 * quotient is an <i>equivalence relation</i> on <tt>C</tt>, and that the
 * natural ordering is a <i>total order</i> on <tt>C</tt>.  When we say that a
 * class's natural ordering is <i>consistent with equals</i>, we mean that the
 * quotient for the natural ordering is the equivalence relation defined by
 * the class's {@link Object#equals(Object) equals(Object)} method:<pre>
 *     {(x, y) such that x.equals(y)}. </pre><p>
 *
 * This interface is a member of the
 * <a href="{@docRoot}/../technotes/guides/collections/index.html">
 * Java Collections Framework</a>.
 *
 * @param <T> the type of objects that this object may be compared to
 *
 * @author  Josh Bloch
 * @see java.util.Comparator
 * @since 1.2
 */

这一接口会对实现了它的类施加一个整体的顺序.这一顺序被认为是类的自然顺序,类的比较方法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方法定义的等价关系.


public interface Comparable<T> {

    public int compareTo(T o);
}

将当前对象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.

可能很多人会搞混与Comparatore的区别
Comparator是比较接口,我们如果需要控制某个类的次序,而该类本身不支持排序(即没有实现Comparable接口),那么我们就可以建立一个“该类的比较器”来进行排序,这个“比较器”只需要实现Comparator接口即可。

Comparable是排序接口,若一个类实现了Comparable接口,就意味着“该类支持排序”。而Comparator是比较器,我们若需要控制某个类的次序,可以建立一个“该类的比较器”来进行排序。

Comparable相当于“内部比较器”,而Comparator相当于“外部比较器”。

两种方法各有优劣, 用Comparable 简单, 只要实现Comparable 接口的对象直接就成为一个可以比较的对象,但是需要修改源代码。 用Comparator 的好处是不需要修改源代码, 而是另外实现一个比较器, 当某个自定义的对象需要作比较的时候,把比较器和对象一起传递过去就可以比大小了, 并且在Comparator 里面用户可以自己实现复杂的可以通用的逻辑,使其可以匹配一些比较简单的对象,那样就可以节省很多重复劳动了。

部分取材自:
https://www.cnblogs.com/xujian2014/p/5215082.html

整理不易,喜欢请点赞

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,761评论 5 460
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,953评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,998评论 0 320
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,248评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,130评论 4 356
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,145评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,550评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,236评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,510评论 1 291
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,601评论 2 310
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,376评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,247评论 3 313
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,613评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,911评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,191评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,532评论 2 342
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,739评论 2 335

推荐阅读更多精彩内容