小编典典
你可以使对象具有可比性:
public static class MyObject implements Comparable {
private Date dateTime;
public Date getDateTime() {
return dateTime;
}
public void setDateTime(Date datetime) {
this.dateTime = datetime;
}
@Override
public int compareTo(MyObject o) {
return getDateTime().compareTo(o.getDateTime());
}
}
然后通过调用以下命令对其进行排序:
Collections.sort(myList);
但是,有时你不想更改模型,例如想要对几个不同的属性进行排序时。在这种情况下,你可以动态创建比较器:
Collections.sort(myList, new Comparator() {
public int compare(MyObject o1, MyObject o2) {
return o1.getDateTime().compareTo(o2.getDateTime());
}
});
但是,仅当你确定比较时dateTime不为null时,以上方法才有效。明智的是,还应处理null以避免NullPointerExceptions:
public static class MyObject implements Comparable {
private Date dateTime;
public Date getDateTime() {
return dateTime;
}
public void setDateTime(Date datetime) {
this.dateTime = datetime;
}
@Override
public int compareTo(MyObject o) {
if (getDateTime() == null || o.getDateTime() == null)
return 0;
return getDateTime().compareTo(o.getDateTime());
}
}
或在第二个示例中:
Collections.sort(myList, new Comparator() {
public int compare(MyObject o1, MyObject o2) {
if (o1.getDateTime() == null || o2.getDateTime() == null)
return 0;
return o1.getDateTime().compareTo(o2.getDateTime());
}
});
2020-03-01