【发布时间】:2014-01-14 03:20:48
【问题描述】:
我正在尝试对 ArrayList 对象中的日期进行排序。为此,我使用排序,其中 dateList 是我的 ArrayList 对象:
Collections.sort(dateList, new DateComparator());
我尝试使用以下 Comparator 类来做到这一点:
class DateComparator implements Comparator {
int compare(Object a, Object b) {
Date x = (Date) a;
Date y = (Date) b;
if (x > y) {
return 1;}
else if (x == y) {
return 0;}
else if (x < y) {
return 1;
}
}
}
但是,这给了我以下错误:
1) 无法实现 compare(T,T) - 试图分配较弱的访问权限;在接口 Comparator 中声明的 T 扩展对象是公共的
2) 二元运算符 '>' 的错误操作数类型: if (x>y) { 第一种:日期第二种:日期
3) 二元运算符 '
关于出了什么问题有什么想法吗?
干杯
【问题讨论】:
-
首先,你不能在日期上使用 。
-
为什么不将日期转换为完整毫秒,然后使用 >,
-
将
x > y更改为x.after(y)等。另外,不要使用==- 使用equals。查看class Date的文档 -
你的第一个问题是不知道如何使用泛型引起的。总的来说,阅读 oracle 的教程应该涵盖你所有的问题docs.oracle.com/javase/tutorial/collections/interfaces/…
标签: java sorting date arraylist