2016-12-02 82 views
2

我想排序事件的結束時間。在我的Event類中的Application類endTime由我的Time類中的小時和分鐘定義。錯誤使用Collections.sort

爲我的活動課程添加了implements Comparable<Event>,但我獲得The type Event must implement the inherited abstract method Comparable<Event>.compareTo(Event)。我嘗試了快速修復add unimplemented methods,但發現很少成功。

ArrayList<Event> events = new ArrayList <Event>(); 

Time endTime = new Time((startTime.getHour()), (startTime.getMinute() + duration)); 

在我的時間I類使用的compareTo

public class Time implements Comparable<Time> { 

@Override 
public int compareTo(Time time){ 
    if (this.getHour() > time.getHour()) 
     return 1; 
    else if (this.getHour() == time.getHour()) 
     return 0; 
    else 
     return -1; 
} 

當我嘗試到ArrayList在我的應用程序類進行排序,我得到

The method sort(List<T>) in the type Collections is not applicable for the arguments (ArrayList<Event>) 

       Collections.sort(events); 
+3

是否'Event'實現可比''? (不清楚爲什麼「時間」類是相關的) –

+0

我的事件應該實現「可比較的」嗎?它沒有'compareTo'。 'compareTo'位於'Time'類中。 – ProgrammingBeginner24

+2

是的。 'Collections.sort'還會怎樣知道如何比較它的實例?除非你告訴'endTime',否則不知道如何排序。 –

回答

0

的Collections.sort()是:

 public static <T extends Comparable<? super T>> void sort(List<T> list) { 
      list.sort(null); 
     }  

所以,應該讓事件實現可比較而不是時間。

0

如果您想進行排序收集基於事件時間那麼事件類應該實現可比界面,並使用從時間類比較法事件的。

只需添加實施可比的接口,以事件等級和比較對象的時間裏面:

public class Event implements Comparable<Event>{ 

    //removed fields and methods 

    @Override 
    public int compareTo(Event event){ 
     return this.getTime().compareTo(event.getTime()); 
    } 

} 
相關問題