我有这样的东西:
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 和 Comparable 的 HashSet 都可以传递给此方法?谢谢!
最佳答案
使用<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;
}
}
关于java - 编写一个通用方法来对一组任意类型的可比较对象进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48981515/