栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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

public static class MyObject implements Comparable<MyObject> {  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<MyObject>() {  public int compare(MyObject o1, MyObject o2) {      return o1.getDateTime().compareTo(o2.getDateTime());  }});

但是,仅当你确定比较时dateTime不为null时,以上方法才有效。明智的是,还应处理null以避免NullPointerExceptions:

public static class MyObject implements Comparable<MyObject> {  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<MyObject>() {  public int compare(MyObject o1, MyObject o2) {      if (o1.getDateTime() == null || o2.getDateTime() == null)        return 0;      return o1.getDateTime().compareTo(o2.getDateTime());  }});


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/373359.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号