java list 参数传递 排序 无效_java – 错误消息:类型集合中的方法sort(List)不适用于参数(ArrayList)...

继续收到错误消息,但不知道为什么.无法使用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 {

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值