【发布时间】:2016-06-11 20:13:33
【问题描述】:
不断收到错误消息,但不知道为什么。无法获取代码以使用 Collections.sort() 对列表进行排序
这就是我所拥有的。 3 个 java 文件。
接口文件。
public interface Comparable<T> {
public int compareTo(T other);
}
类文件。
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;
}
}
}
客户端类
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);
}
}
我得到的错误信息是“集合类型中的方法 sort(List) 不适用于参数 (ArrayList)”
【问题讨论】:
标签: java collections interface