2010-10-29 51 views
1

考慮:比較的通用接口沒有警告

public interface PrimaryKey<Key extends Comparable> { 
    Key getKey(); 
} 

public class PrimaryKeyComparator implements Comparator<PrimaryKey> { 
    public int compare(PrimaryKey first, PrimaryKey second) { 
     return first.getKey().compareTo(second.getKey()); 
    } 
} 

這種組合的作品,但提供有關原始類型的警告。我嘗試過添加類型參數的各種方法,但是我嘗試過的每個組合都會破壞代碼。

+2

使用'Key'和'TKey'作爲通用佔位符是一個非常簡單的方法來迷惑人閱讀你的代碼。 Java使用'E','T','K'和'V'作爲佔位符名稱是有原因的。 – Powerlord 2010-10-29 17:31:13

+0

絕對同意R. Bemrose。 'Key'看起來像一個類或接口的名稱。 – ColinD 2010-10-29 17:41:20

回答

3

試試這個:

public interface PrimaryKey<TKey extends Comparable<TKey>> { 
    TKey getId(); 
} 

public class PrimaryKeyComparator<TKey extends Comparable<TKey>> 
           implements Comparator<PrimaryKey<TKey>> { 
    public int compare(PrimaryKey<TKey> first, PrimaryKey<TKey> second) { 
     return first.getId().compareTo(second.getId()); 
    } 
} 
+0

太棒了!謝謝。 – 2010-10-29 17:33:04

+5

通用參數'TKey'實際上應該是'>',它允許使用實現原始「Comparable」類而不是「Comparable 」或類「Comparable 」類的子類。 – ColinD 2010-10-29 17:38:31