错误消息:Collections类型中的方法sort(List <T>)不适用于参数(ArrayList <Date>)

Kiz*_*zzo 5 java collections interface

不断收到错误消息,但不知道为什么。无法获取代码以使用Collections.sort()对列表进行排序

这就是我所拥有的。3个Java文件。

接口文件。

public interface Comparable<T> {
   public int compareTo(T other);
}
Run Code Online (Sandbox Code Playgroud)

类文件。

public class Date implements Comparable<Date>{

private int year;
private int month;
private int day;

public Date(int month, int day, int year){   
   this.month = month;
   this.day = day;
   this.year = year;
}

public int getYear(){
   return this.year;
}

public int getMonth(){
   return this.month;
}

public int getDay(){
   return this.day;
}
public String toString(){
   return month + "/" + day + "/" + year;
}


public int compareTo(Date other){
    if (this.year!=other.year){
        return this.year-other.year;
    } else if (this.month != other.month){
        return this.month-other.month;
    } else {
        return this.day-other.day;
    }
}
Run Code Online (Sandbox Code Playgroud)

}

客户类

import java.util.*;

public class DateTest{
   public static void main(String[] args){

  ArrayList<Date> dates = new ArrayList<Date>();
  dates.add(new Date(4, 13, 1743)); //Jefferson
  dates.add(new Date(2, 22, 1732)); //Washington
  dates.add(new Date(3, 16, 1751)); //Madison
  dates.add(new Date(10, 30, 1735)); //Adams
  dates.add(new Date(4, 28, 1758)); //Monroe     


  System.out.println(dates);
  Collections.sort(dates);
  System.out.println("birthdays = "+dates);

}




}
Run Code Online (Sandbox Code Playgroud)

我得到的错误消息是“类型Collections中的方法sort(List)不适用于参数(ArrayList)”

Sle*_*idi 5

因为Collections.sortexpectsjava.lang.Comparable而不是您的 Comparable 接口,请更改您的Date类以实现java.lang.Comparable.

public class Date implements java.lang.Comparable<Date>{
 ..
}
Run Code Online (Sandbox Code Playgroud)

如果由于某些原因你仍然想定义你自己的 Comparable 并且你仍然想使用 Collections.sort 那么你Comparable必须是java.util.Comparable

interface Comparable<T> extends java.lang.Comparable<T> {

}
Run Code Online (Sandbox Code Playgroud)