Comparable和Comparator都是用来实现集合中元素的比较、排序的。 Comparable是在集合内部定义的方法实现的排序,位于java.lang下。 Comparator是在集合外部实现的排序,位于java.util下。
Comparable是一个对象本身就已经支持自比较所需要实现的接口,如String、Integer自己就实现了Comparable接口,可完成比较大小操作。自定义类要在加入list容器中后能够排序,也可以实现Comparable接口,在用Collections类的sort方法排序时若不指定Comparator,那就以自然顺序排序。所谓自然顺序就是实现Comparable接口设定的排序方式。
Comparator是一个专用的比较器,当这个对象不支持自比较或者自比较函数不能满足要求时,可写一个比较器来完成两个对象之间大小的比较。Comparator体现了一种策略模式(strategy design pattern),就是不改变对象自身,而用一个策略对象(strategy object)来改变它的行为。
总而言之Comparable是自已完成比较,Comparator是外部程序实现比较。
Comparator
public class AbsComparator<T> implements Comparator<T>{public int compare(Object o1, Object o2){int ovalue1 = Math.abs(((Integer) o1).intValue());int ovalue2 = Math.abs(((Integer) o2).intValue());return (ovalue1 > ovalue2) ? 1 : (ovalue1 == ovalue2 ? 0 : -1); }}import java.util.Arrays;import java.util.Random;public class AbsComparatorTest{public static void main(String[] args){// 使用方法1Random rn = new Random();Integer[] integerArray = new Integer[20];for (int i = 0; i < integerArray.length; i++) { integerArray[i] = new Integer(rn.nextInt(100) * (rn.nextBoolean() ? 1 : -1)); }System.out.PRintln("用Integer内置方法排序:");Arrays.sort(integerArray);System.out.println(Arrays.asList(integerArray));System.out.println("用AbsComparator排序:");Arrays.sort(integerArray, new AbsComparator<Integer>());System.out.println(Arrays.asList(integerArray));// 使用方法2System.out.println("用AbsComparator比较-100和10的绝对值大小结果是:");AbsComparator<Integer> absComparator = new AbsComparator<Integer>();int result = absComparator.compare(new Integer(-100), new Integer(10));System.out.println(result); }}Comparable
class TestAge implements Comparable<Object>{ private int age; public TestAge(int age){ this.age=age; } @Override public int compareTo(Object o) { return this.age -((TestAge)o).age ; } }可以看出Comparator为一个比较器,而Comparable为一个比较接口。 一个类实现了Camparable接口则表明这个类的对象之间是可以相互比较的,这个类对象组成的集合就可以直接使用sort方法排序。 Comparator可以看成一种算法的实现,将算法和数据分离,Comparator也可以在下面两种环境下使用: 1、类的设计师没有考虑到比较问题而没有实现Comparable,可以通过Comparator来实现排序而不必改变对象本身 2、可以使用多种排序标准,比如升序、降序等
新闻热点
疑难解答