【问题标题】:Error using Collections.sort使用 Collections.sort 时出错
【发布时间】:2017-04-17 03:14:00
【问题描述】:

我正在尝试对事件的结束时间进行排序。在我的应用程序类中,endTime 位于我的 Event 类中,由我的 Time 类中的小时和分钟定义。

在我的事件类中添加了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));

在我的时间课程中,我使用 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);

【问题讨论】:

  • Event 是否实现了Comparable&lt;Event&gt;? (不清楚为什么Time 类是相关的)
  • 我的事件应该实现Comparable&lt;Event&gt; 吗?它没有compareTocompareTo 位于 Time 类中。
  • 是的。 Collections.sort 怎么知道如何比较它的实例?它不知道对endTime 进行排序,除非你告诉它。

标签: java sorting oop arraylist collections


【解决方案1】:

Collections.sort() 是:

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

所以,应该使 Event 实现具有可比性而不是 Time。

【讨论】:

    【解决方案2】:

    如果您想根据事件时间事件集合进行排序,那么 Event 类应该实现 Comparable 接口并使用 Time 类中的 compare 方法。

    只需将 Comparable 接口的实现添加到 Event 类并比较其中的 Time 对象:

    public class Event implements Comparable<Event>{
    
        //removed fields and methods
    
        @Override
        public int compareTo(Event event){
           return this.getTime().compareTo(event.getTime());
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-22
      • 2020-01-16
      • 2013-08-15
      • 2018-06-05
      • 1970-01-01
      • 2013-09-16
      • 1970-01-01
      相关资源
      最近更新 更多