import java.util.*; class DescType implements Comparator { public int compare(Object o1, Object o2) { Integer i = (Integer)o1; Integer j = (Integer)o2; return (i<j?1:(i==j?0:-1)); } } public class Hello { public static void main(String[] args) { Integer a[] = {3, 1, 2}; Arrays.sort(a, new DescType()); for(int i:a) System.out.println(i); } }
Q:由上代码: x<y为1即为真。。。也就是第一个参数比第二个参数小为真。。应该是升序排列,这里却是降序排列的,怎么理解??
A:compare函数的机制是自定义下若o1>o2则返回1,而上面的代码中若1<2会返回1,即在上面的自定义下,其实1是大于2的(即compare(1,2)=1),同理,2也会大于3.那么Array.sort()从小到大排序时其实3是最小的,故输出321,表面上是逆序了,实际是符合上面compare函数中的定义的,还是从小到大输出,只不过上面自定义下3是比1小的。
另外,Collections.sort(),Arrays.sort() 默认就是升序排列的(如API所说:
Sorts the specified list into ascending order, according to the natural ordering of its elements. All elements in the list must implement the Comparable interface)。
其实,明白了Comparator比较器的原理,就可以实现自定义排序了。
用 Comparator 是策略模式(strategy design pattern),就是不改变对象自身,而用一个策略对象(strategy object)来改变它的行为。