java按日期和时间对ArrayList的对象进行排序
我在ArrayList
中有10个对象,其中患者ID和预约日期作为实例变量。如何按预约日期对患者进行分类
由于某些原因,我无法使用Comparator
对ArrayList
进行排序;编译器给出了一个错误:
java.util.Comparator is abstract; cannot be instantiated
当不使用Comparator
时Collections.sort()
对Object
不起作用
ArrayList<Appointment> testApp = new ArrayList<>();
while (!App.isEmpty()) {
tempA = (Appointment) App.dequeue();
if (tempA.getPatID().equals(search)) {
testApp.add(tempA);
}
tempApp.enqueue(tempA);
}
while (!tempApp.isEmpty()) {
tempA = (Appointment) tempApp.dequeue();
App.enqueue(tempA);
}
Collections.sort(testApp, new Comparator<Appointment>());
# 1 楼答案
您不能直接实例化
Comparator
,您需要自己实现逻辑,请列出使用lambda表达式,可以编写如下代码:
如果
Appointment
是您自己编写的类,则可以使其实现Comparable<Appointment>
:这意味着您可以在不指定比较器的情况下对列表进行排序:
# 2 楼答案
我假设您的
Appointment
类如下所示:如果是这样,您应该创建一个} 方法进行排序:
Comparator
来使用^{lambda函数告诉比较器如何获取对象(一个
Appointment
)并提取用于排序的元素(键;appointmentDate
)。如果您愿意,可以将其浓缩为方法引用:您也可以直接在} :
ArrayList
上调用^{如果您总是(或通常)按日期排序您的^ {< CD1>}对象,则可以考虑使^ {CD1>}实现^{} ,这样您就可以调用^ {< CD11>}而不传递^ {< CD2>}:
# 3 楼答案
# 4 楼答案
为了使您的类实例彼此具有可比性,您的类大多数实现“可比”接口。例如,如果您有一个名为C1的类,并且您希望使C1实例具有可比性,则大多数情况下会以以下方式声明C1:
现在,如果您使用
Collections.sort()
,您的arrayList将被排序