我有这样的事情:
public class A implements Comparable<A> {
...
@Override
public int compareTo(A obj) {
...
}
}
public class B implements Comparable<B> {
...
@Override
public int compareTo(B obj) {
...
}
}
我还有一堆 HashSet 集合,它们在程序运行过程中慢慢填充,例如:
private Collection<A> col = new HashSet<A>();
在程序的最后,我想将它们转换为排序列表,以便它们可以排序显示:
public class Utils {
public static <T> Collection<Comparable<T>> toSortedList(Collection<Comparable<T>> col) {
List<Comparable<T>> sorted = new ArrayList<Comparable<T>>(col);
Collections.sort(sorted);
return sorted;
}
}
不幸的是,我收到编译错误:
The method sort(List<T>) in the type Collections is not applicable for the arguments (List<Comparable<T>>)
如何修改上述内容,以便 Comparable<A> 和 Comparable<B> 的 HashSets 可以传递给此方法?谢谢!
使用<T extends Comparable<? super T>>
通用语法:
public class Utils {
public static <T extends Comparable<? super T>> Collection<T> toSortedList(Collection<T> col) {
List<T> sorted = new ArrayList<T>(col);
Collections.sort(sorted);
return sorted;
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句