comparator接口与compare方法的实现
刷leetcodecode时看到一道题需要利用自定义的比较器进行排序,最开始一头雾水,看了API终于懂了~
Arrays.sort(T[] a,Comparator<? super T> c)可以根据比较器的compare方法对数组进行排序,compare方法的不同实现对应着不同的排序准则;
可以看到API中关于compare方法的解释如下:
int compare(T o1,T o2)
In the foregoing description, the notation sgn(expression) designates the mathematical signum function, which is defined to return one of -1, 0, or 1 according to whether the value of expression is negative, zero or positive.
The implementor must ensure that sgn(compare(x, y)) == -sgn(compare(y, x)) for all x and y. (This implies that compare(x, y) must throw an exception if and only if compare(y, x) throws an exception.)
The implementor must also ensure that the relation is transitive: ((compare(x, y)>0) && (compare(y, z)>0)) implies compare(x, z)>0.
Finally, the implementor must ensure that compare(x, y)==0 implies that sgn(compare(x, z))==sgn(compare(y, z)) for all z.
It is generally the case, but not strictly required that (compare(x, y)==0) == (x.equals(y)). Generally speaking, any comparator that violates this condition should clearly indicate this fact. The recommended language is "Note: this comparator imposes orderings that are inconsistent with equals."
- 参数:
o1
- the first object to be compared.o2
- the second object to be compared.- 也就是说compare方法根据其返回值确定比较对象的大小,如果返回值为正,认为o1>o2;返回值为负,认为o1<o2;返回值为0,认为两者相等;
-
public class SortByComparator{ //升序排列 public static void sortAscend(Integer[] a){ Arrays.sort(a, new Comparator<Integer>() { public int compare(Integer a, Integer b) { return a.compareTo(b); } }); } //降序排列,如果b.compareTo(a)>0,则compare方法根据其返回值认为a>b,与自然比较结果相反 public static void sortDescend(Integer[] a){ Arrays.sort(a, new Comparator<Integer>() { public int compare(Integer a, Integer b) { return b.compareTo(a); } }); } public static void main(String[] args) { Integer[] a={1,2,3}; //升序排列 sortAscend(a); for(int num:a) System.out.println(num); //降序排列 sortDescend(a); for(int num:a) System.out.println(num); }
}输出
1 2 3 3 2 1
注:Arrays.sort(T[] a,Comparator<? super T> c)默认为升序排列
-