2016-12-02 48 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()); 
    } 

} 
相关问题