public interface Comparable<T>
This interface imposes a total ordering on the objects of each class that
implements it. This ordering is referred to as the class‘s natural
ordering, and the class‘s compareTo method is referred to as its
natural comparison method.
Lists (and arrays) of objects that implement this interface can be sorted
automatically by Collections.sort
(and Arrays.sort
).
Objects that implement this interface can be used as keys in a sorted
map or as elements in a sorted set, without the need to
specify a comparator.
Comparable接口会给每个实现了该接口的类的对象指定一个顺序,这个顺序是类的自然顺序。一个List中的所有对象都实现了这个接口,那么可以通过Collection.sort()方法对它们进行排序。实现了该接口的对象可以作为sorted map的key或者sorted set的元素,不需要再指定一个comparator。
它只有一个方法:int compareTo(T o)
---------------------------------------------------------------------------------------
public interface Comparator<T>
A comparison function, which imposes a total ordering on some collection
of objects. Comparators can be passed to a sort method (such as Collections.sort
or Arrays.sort
)
to allow precise control over the sort order.
Comparator接口给对象的集合提供一个比较的功能。比较器能够被传递到一个排序的方法(比如:Collections.sort或者Arrays.sort)中来精确控制排序的顺序。
它有两个方法:
int compare(T o1, T o2)
boolean equals(Object obj)
总结一下:
- 实现了Comparable接口的对象自身就具备比较功能,而实现了Comparator接口的对象是一个比较器,也就是一个工具,它用于比较那些需要比较的对象。
- 利用Collections.sort(List<T> list)方法进行排序的对象必须实现Comparable接口
- 可以利用Collections.sort(List<T> list, Comparator<? super T> c)方法进行排序,排序规则自己指定