错误信息:Collections 类型中的 sort(List<T>) 方法不适用于参数 (ArrayList<Date>) [英] Error Message: The method sort(List<T>) in the type Collections is not applicable for the arguments (ArrayList<Date>)
问题描述
不断收到错误消息,但不知道为什么.无法获取使用 Collections.sort() 对列表进行排序的代码
Keep getting error message, but don't know why. Can't get code to sort the list using Collections.sort()
这是我所拥有的.3个java文件.
Here is what I have. 3 java files.
接口文件.
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)"
The error message I get is "The method sort(List) in the type Collections is not applicable for the arguments (ArrayList)"
推荐答案
因为 Collections.sort
需要 java.lang.Comparable
而不是你的 Comparable 接口,改变你的 Date
类来实现java.lang.Comparable
.
Because Collections.sort
expects java.lang.Comparable
and not your Comparable interface, change your Date
class to implement the java.lang.Comparable
.
public class Date implements java.lang.Comparable<Date>{
..
}
如果由于某些原因你仍然想定义你自己的 Comparable 并且你仍然想使用 Collections.sort 那么你的 Comparable
必须是 java.util.Comparable
If you still want to define your own Comparable for some reasons and you still want to use Collections.sort then the your Comparable
has to be java.util.Comparable
interface Comparable<T> extends java.lang.Comparable<T> {
}
这篇关于错误信息:Collections 类型中的 sort(List<T>) 方法不适用于参数 (ArrayList<Date>)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!