2016-08-24 67 views
1

與仿製藥需要幫助,我有這個類:如何使用通用Treeset創建比較器?

public class Course<T> { 

    private T idOrName; 
    private float avg; 

    public Course(T idOrName,float avg){ 
     this.idOrName=idOrName; 
     this.avg=avg; 

    } 


} 

....我需要做字符串或整數之間的用戶選擇,然後創建一個TreeSet,並通過該仿製藥對其進行排序type.how我可以這樣做,如果我不知道它的數字或字符串?我有做的比較問題:

Set<Course<?>> list=new TreeSet<>(new Comparator<Course<?>(){ 

     @Override 
     public int compare(Course<?> o1, Course<?> o2) { 
      // TODO Auto-generated method stub 
      return 0; 
     } 

    }); 
+0

你爲什麼不只是使用零參數'TreeSet'構造? –

+0

是的,但我需要比較包含字符串或整數的'課程' – dan

+0

該集合是否包含混合類型的條目?即有些是字符串,有些是整數課程? –

回答

1

首先你需要指出的是未來繼續

public class Course<T extends Comparable<T>> { 
    ... 
} 

,預期類必須是Comparable那麼你一般比較可能是這樣的:

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() 
     ); 
    } 
}); 
+0

好吧..試試這個..但最新的不同之處延伸到實施..當我需要嘗試兩個? – dan

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);