Java Comparable and Comparator

reference: https://www.geeksforgeeks.org/comparable-vs-comparator-in-java/
这两者都是属于collection的一员。他们都是实现集合中的元素的比较排序的。
下面分别来说:
Comparable是一个接口 任何类 只要想实现实例之间的比较 比如说整数类(但是字符串类就是一个反例)都要implement Comparable,然后需要在类的内部实现compareTo的方法。
如果我们就按照定义好的比较方法来比较 那么就是默认比较方法 所以在我们可以直接Collections.sort()…
同样 Comparator也是一个接口,内部同样也需要实现compare方法,但是实现comparator的类 就可以作为一个比较器类,可以传入诸如像Collection.sort(list, new xxx())里面。

To summarize, if sorting of objects needs to be based on natural order then use Comparable whereas if you sorting needs to be done on attributes of different objects, then use Comparator in Java.

两者有什么区别
1、Comparator在集合(即你要实现比较的类)外进行定义的实现,而Comparable接口则是在你要比较的类内进行方法的实现。这样看来Comparator更像是一个专用的比较器。
2、Comparator实现了算法和数据的分离,从代码也可以看出,其实这和第一点是相辅相成的,因为Comparable依赖于某一个需要比较的类来实现。
3、Comparable支持自比较,自比较是指比如String等类里面本身就有CompareTo()方法,直接就可以进行String类对象的比较,这也可以从较之Comparator,Comparable中Arrays.sort()方法中只带数组参数的形式与书上例子更相似这点看出。
4、从第3点延伸,我们可以看到当不满足于自比较函数,如String类时,我们试图改写规则要怎么办——通过Comparator因为它支持外比较,它是分离的。
5、当一个又一个类设计完成后,或许我们最初没有设想到类的比较问题,而没使用Comparable接口,那我们之后可以通过Comparator来完成,而同时无需改变之前完成的类的构建。
6、运用Arrays.sort()方法时,注意二者的参数不同,Comparator多了一个参数,这第二个参数是使用Comparator接口的那个被视为专用比较器的类的对象。

English Explain:
They are both interfaces to sort objects
A compatible object is capable of comparing itself with another object, the class itself must implement the Comparable interface to compare its instances;
Comparator is external to the element type we are comparing, that means, we need to create multiple separate classes which implement Comparator to compare by different members

posted @ 2020-10-29 10:16  EvanMeetTheWorld  阅读(10)  评论(0)    收藏  举报