需要帮助泛型,我有这个课程:
public class Course<T> {
private T idOrName;
private float avg;
public Course(T idOrName,float avg){
this.idOrName=idOrName;
this.avg=avg;
}
}
....我需要让用户在String或Integer之间进行选择,然后创建一个Treeset并按照这个泛型类型对它进行排序。如果我不知道它的数字或字符串,我可以这样做吗?我在制作比较器时遇到问题:
Set<Course<?>> list=new TreeSet<>(new Comparator<Course<?>(){
@Override
public int compare(Course<?> o1, Course<?> o2) {
// TODO Auto-generated method stub
return 0;
}
});
答案 0 :(得分:1)
去复制字段。任何其他解决方案都会更具间接性。在这里,我添加了一个toString
来统一两种情况。
public class Course {
private int id;
private String name;
private float avg;
public Course(int id, float avg){
this(id, "", avg);
}
public Course(String name, float avg){
this(0, name, avg);
}
private Course(int id, String name, float avg){
this.id = id;
this.name = name;
this.avg = avg;
}
@Override
public String toString() {
return id != 0 ? String.value(id) : name;
}
}
和比较器(自java 8起):
Comparator.comparingInt(course -> course.id)
.thenComparing(course -> course.name);
Comparator.comparingInt(Course::getId)
.thenComparing(Course::getName);