Java 编写对任何类型的可比数据集进行排序的通用方法
我有这样的想法:Java 编写对任何类型的可比数据集进行排序的通用方法,java,generics,collections,Java,Generics,Collections,我有这样的想法: public class A implements Comparable<A> { ... @Override public int compareTo(A obj) { ... } } public class B implements Comparable<B> { ... @Override public int compareTo(B obj) { ... } } 公共类A实现了可比性{ .
public class A implements Comparable<A> {
...
@Override
public int compareTo(A obj) {
...
}
}
public class B implements Comparable<B> {
...
@Override
public int compareTo(B obj) {
...
}
}
公共类A实现了可比性{
...
@凌驾
公共国际比较(A obj){
...
}
}
B类公共设施{
...
@凌驾
公共国际比较(B obj){
...
}
}
我还有一组哈希集集合,它们在程序过程中缓慢填充,例如:
private Collection<A> col = new HashSet<A>();
private Collection col=new HashSet();
在程序的最后,我想将它们转换为已排序的列表,以便按顺序显示:
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;
}
}
公共类Utils{
公共静态集合到分类列表(集合列){
列表排序=新数组列表(列);
集合。排序(已排序);
返回排序;
}
}
不幸的是,我得到了编译错误:
The method sort(List<T>) in the type Collections is not applicable for the arguments (List<Comparable<T>>)
类型集合中的方法排序(列表)不适用于参数(列表)
如何修改上述内容,以便将Compariable和Compariable的哈希集传递给此方法?谢谢 Use
Use查看该sort
方法的声明,并复制其对泛型参数的使用。用T
替换你的Comparable
。@Sotirios Delimanolis如果我用T代替Comparable,编译器会抱怨“方法排序”(Listpublic static@Louis Wasserman谢谢你的工作!看看sort
方法的声明,并复制它对泛型参数的使用。将你的Comparable
替换为T
无处不在。@Sotirios Delimanolis如果我用T代替Comparable,编译器会抱怨“方法排序”(Listpublic static@Louis Wasserman谢谢你这么做!
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;
}
}