comparator接口與compare方法的實現


  刷leetcodecode時看到一道題需要利用自定義的比較器進行排序,最開始一頭霧水,看了API終於懂了~

  Arrays.sort(T[] a,Comparator<? super T> c)可以根據比較器的compare方法對數組進行排序,compare方法的不同實現對應着不同的排序准則;

可以看到API中關於compare方法的解釋如下:

int compare(T o1,T o2)
Compares its two arguments for order. Returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.

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)默認為升序排列

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM