目录
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);
有两个入参,实现的是传入的两个对象的比较,而不要求这两个对象本身具有比较能力。