给定:
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());
}
}
此组合有效,但会给出有关原始类型的警告。我尝试了多种添加类型参数的方法,但我尝试过的每一种组合都会破坏代码。
最佳答案
试试这个:
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());
}
}
关于java - 没有警告的通用接口(interface)比较器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4054342/