需要泛型方面的帮助,我有这个类:
public class Course<T> {
private T idOrName;
private float avg;
public Course(T idOrName,float avg){
this.idOrName=idOrName;
this.avg=avg;
}
}
....我需要让用户在字符串或整数之间进行选择,然后创建一个树集并按此泛型类型对其进行排序。如果我不知道它是数字还是字符串,我该怎么做?我在制作比较器时遇到问题:
Set<Course<?>> list=new TreeSet<>(new Comparator<Course<?>(){
@Override
public int compare(Course<?> o1, Course<?> o2) {
// TODO Auto-generated method stub
return 0;
}
});
最佳答案
首先,您需要通过继续下一步来表明预期的类必须是Comparable
public class Course<T extends Comparable<T>> {
...
}
那么你的通用比较器可能是这样的:
Set<Course<?>> list = new TreeSet<>(new Comparator<Course<?>>(){
@Override
public int compare(Course<?> o1, Course<?> o2) {
// If idOrName are both of the same class then we use the
// comparator of this class as we know that they are Comparable
if (o1.idOrName.getClass() == o2.idOrName.getClass()) {
return ((Comparable)o1.idOrName).compareTo((Comparable)o2.idOrName);
}
// If they are not of the same class we compare the name of the class
return o1.idOrName.getClass().getName().compareTo(
o2.idOrName.getClass().getName()
);
}
});
关于java - 如何使用通用 Treeset 创建比较器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39118973/