我们在教程中制作了一个具有以下签名的示例(作为界面的一部分)
<T> List<Comparable<T>> sort(Collection<Comparable<T>> c, boolean ascending);
我们发现几乎不可能在没有警告的情况下实现该方法:
public <T> List<Comparable<T>> sort(Collection<Comparable<T>> c, boolean ascending) {
List<T> list = new ArrayList<T>();
Collections.sort(list);
return list;
}
我们得到的 Collections.sort(list)
行中的错误是:
Bound mismatch: The generic method sort(List<T>) of type Collections is not
applicable for the arguments (List<T>). The inferred type T is not a valid
substitute for the bounded parameter <T extends Comparable<? super T>>
但是,它适用于以下签名:
<T extends Comparable<T>> List<T> sort(Collection<T> c, boolean ascending);
有了这个签名,上面的代码(sort
的实现)就可以按预期工作了。我想知道这是什么原因。
最佳答案
列表Comparable<T>
s 是与 T
相当的对象列表秒。不能说这些对象本身是否是 T
秒。因此,不可能将两个元素相互比较。
T
s,这恰好与其他 T
相当s,可以相互比较。所以对这样的列表进行排序 T
s 是可能的。
关于java - Java 中通用签名的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12931726/