无警告的通用接口比较器

时间:2010-10-29 17:22:34

标签: java generics comparator

假设:

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());
    }
}

此组合有效,但会提供有关原始类型的警告。我已经尝试了各种方法来添加类型参数,但我尝试过的每个组合都会破坏代码。

1 个答案:

答案 0 :(得分: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());
    }
}