首页 > 代码库 > Comparable与Comparator的区别
Comparable与Comparator的区别
一。比较
Comparable & Comparator 都是用来实现集合中元素的比较、排序的,只是 Comparable 是在内部实现的排序,Comparator 是在外部实现的排序。
用 Comparator 是策略模式(strategy design pattern),不改变对象自身,而用一个策略对象(strategy object)来改变它的行为。
比如:你想对整数采用绝对值大小来排序,Integer 是不符合要求的,你不需要去修改 Integer 类(实际上你也不能这么做)去改变它的排序行为,只要
使用一个实现了 Comparator 接口的对象来实现控制它的排序就行了。
二。介绍
1.java.util.Comparator
int compare(T o1, T o2)
boolean equals(Object obj)
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. Comparators can also be used to
control the order of certain data structures (such as sorted sets
or sorted maps
), or to provide an ordering for collections of objects
that don‘t have a natural ordering
.
public static <T> void sort(List<T> list, Comparator<? super T> c)
2.java.lang.Comparable
int compareTo(T o)
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.