2016-12-03 66 views
0

我一直有這個問題幾天,不能通過它。我有一個數組列表存儲。排序陣列元素的問題

public class Application { 

Time startTime = new Time(hour,minute); 
Time endTime = new Time((startTime.getHour()), (startTime.getMinute() + duration)); 
Event e1 = new Event("Lecture", title, startTime, endTime); 

我想根據我的結束時間我的事件進行梳理,我發現了問題是,結束時間是基於開始時間,它使用的小時和分鐘從我Time類。當我嘗試使用compareTo時,我感到困惑。我把它放在我的Time類中,但後來意識到必須在我的Event類中比較實例。我如何使用compareTo來比較endTimes,以及如何輸出排序。當我已經把的compareTo在我的活動我

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

      Collections.sort(events); 

public Event(String type, String title, Time startTime, Time endTime) { 
    this.type = type; 
    this.title = title; 
    this.startTime = startTime; 
    this.endTime = endTime; 
} 

private int minute; 

public Time(int hour, int minute) { 
    this.minute = hour * 60 + minute; 
} 

也可能我extend類,否則我就必須實現它使用compareTo

回答

0

我將如何使用的compareTo比較endTimes,

Event類會叫你的TimecompareTo方法,並使用結果作爲部分○compareTo方法f決定事件的順序。

以及如何輸出排序。

一種方法是使用一個循環,並printprintln電話。

當我已經把中的compareTo我的活動我:"The method sort(List<T>) in the type Collections is not applicable for the arguments (ArrayList<Event>)"

聲明的events類型爲List<Event>

順便說一下,在事件中放置compareTo並不會導致這種情況。這是由另一個變化/另一個錯誤造成的。

我也可以擴展一個類,否則我就必須實現它使用的compareTo

需要具有可比性的需要「落實」的Comparable接口與自己類型的任何類類型參數;例如

public class Event implements Comparable<Event> { 

然後它需要提供一個compareTo方法的實現。

+0

如何從我的'eventTo'中的'compareTo'在我的'Time'類中調用'compareTo'方法? – ProgrammingBeginner24

+0

與在對象實例上調用* any *方法的方式相同! –