[英]how to create comparator with generic Treeset?
需要泛型的幫助,我有這個課程:
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並按此泛型類型對其進行排序。如果我不知道它是數字還是String怎么辦? 我在制作比較器時遇到問題:
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()
);
}
});
去重復字段。 任何其他解決方案都將更加環境。 在這里,我添加了一個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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.