2014-03-05 37 views
1

我有一個比較器,在給定列反向後對數組進行排序。我希望這個比較器不適用於int [],它也可以用於其他數字類型。我該怎麼做?如何將Reverse Comparator重寫爲泛型?

比較器的代碼是在這裏:

public class ReverseComparator implements Comparator<int[]> { 

int col; 

public ReverseComparator(int col) { 

    this.col = col; 

} 

@Override 
public int compare(int[] a, int[] b) { 

    if (a[col - 1] > b[col - 1]) { 
     return -1; 
    } else if (a[col - 1] < b[col - 1]) { 
     return 1; 
    } else { 
     return 0; 
    } 

} 

} 

我改變它,但它永遠是錯的,我不知道......

public class ReverseComparator implements Comparator<T extends Number[]> { 

int col; 

public ReverseComparator(int col) { 

    this.col = col; 

} 

@Override 
public int compare(T[] a, T[] b) { 

    if (a[col - 1] > b[col - 1]) { 
     return -1; 
    } else if (a[col - 1] < b[col - 1]) { 
     return 1; 
    } else { 
     return 0; 
    } 

} 

} 
+0

'它總是錯'意思是排序不正確? – Kick

+0

他想分類任何東西的數組。你不能擴展Number [],這就是爲什麼它是錯誤的 – webuster

+0

@Youngistan不,第一個比較器是好的,它只是爲int []工作。第二個比較器不起作用。 – xirururu

回答

5

如果你必須做出ReverseComparator通用,那麼你必須用它來聲明類型參數。並給它的界限:

public class ReverseComparator<T extends Number & Comparable<T>> implements Comparator<T[]> { 
    @Override 
    public int compare(T[] a, T[] b) { 
     // Write your comparison logic here 
     // Note that just normal arithmetic operators won't work here. 
    } 
} 

我已經給了類型參數的兩個邊界,因爲我們只想比較可比較的數字。將Comparable<T>作爲第二界限允許您使用compareTo()方法進行比較。

另請注意,這不適用於原始類型數組,例如,int[][]。您必須有Integer[][]Float[][]等。

+0

我試過這段代碼,但如果我給出下面的代碼,它告訴我錯了:public int compare(T [] a,T [] b){if(a [1]> b [1]){return -1 ;}}錯誤是:運算符>未定義爲參數類型,您知道它有什麼問題嗎? – xirururu

+0

@xirururu什麼是錯誤? –

+0

我試過這段代碼,但是如果我給出下面的代碼,它告訴我錯了:public int compare(T [] a,T [] b){if(a [1]> b [1]){return -1 ;}}錯誤是:運算符>未定義爲參數類型,您知道它有什麼問題嗎? – xirururu

2

Java庫中已有一個解決方案:Collections.reverseOrder可以選擇使用另一個比較器。

這適用於實現Compareable接口的對象:

public class ColumnComparator<T> implements Comparator<T extends Compareable[]> { 

    // Should not change in the middle of the comparison 
    final int col; 

    public ColumnComparator<T>(int col) { 

     this.col = col; 

    } 

    @Override 
    public int compare(T[] a, T[] b) { 
    // Watch it! Possible null pointer if a[col-1] == null! Change as it suits yourself 
    // The generic implements the Comparable interface. Use it. 
    return a[col -1 ].compareTo(b[col-1]); 

    } 

    } 

然後,鏈與反向比較的比較器的一個實例:

Comparator<ClassYouWantToCompare[]> columnComparator = new ColumnComparator<ClassYouWantToCompare[]>(1); 
    // Reverse the odering of the comparator. 
    Comparator<ClassYouWantToCompare[]> result = Collections.reverseOrder(columnComparator); 

這隻會導致result.compareTo(Compareable a, Compareable b) == -1 * columnComparator.compareTo(T a, T b)但票價更具可讀性。

+0

。錯誤是:「在這一行多個標記 \t - 令牌語法錯誤‘>’,{預期後 \t此令牌 \t - 語法上的標記錯誤‘擴展’,預計」 – xirururu

+0

我忘了類的參數(ColumnComparator )。我已經更新了代碼,它現在應該可以工作。 – user3001