继续收到错误消息,但不知道为什么.无法使用Collections.sort()获取代码来对列表进行排序
这就是我所拥有的. 3个java文件.
接口文件.
public interface Comparable {
public int compareTo(T other);
}
类文件.
public class Date implements Comparable{
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;
}
}
}
客户端类
import java.util.*;
public class DateTest{
public static void main(String[] args){
ArrayList dates = new ArrayList();
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);
}
}
我得到的错误消息是“类型集合中的方法排序(列表)不适用于参数(ArrayList)”
最佳答案 因为Collections.sort需要java.lang.Comparable而不是Comparable接口,所以更改Date类以实现java.lang.Comparable.
public class Date implements java.lang.Comparable{
..
}
如果您仍然想要出于某些原因定义自己的Comparable并且仍然想要使用Collections.sort,那么您的Comparable必须是java.util.Comparable
interface Comparable extends java.lang.Comparable {
}