java日期排序_Java 按日期对ArrayList中的对象进行排序?

本文介绍了如何使Java对象具有可比性,通过实现Comparable接口对对象列表进行排序。同时,当需要对多个属性排序或者不希望修改模型时,可以使用动态创建的Comparator。示例展示了如何处理可能的null值,以避免NullPointerException。
摘要由CSDN通过智能技术生成

小编典典

你可以使对象具有可比性:

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值