【问题标题】:How to sort ArrayLists? [duplicate]如何对 ArrayList 进行排序? [复制]
【发布时间】:2012-10-01 10:51:17
【问题描述】:

我有一些列表包含 DataTime(Joda-time) 类型的元素。如何按日期对它们进行排序? 如果有人给出示例的链接,那就太好了...

【问题讨论】:

  • 查看Collections.sortComparator
  • @nkr 我想你的意思是比较器
  • 提示:按时间戳排序。
  • @JordanKaye:糟糕,谢谢 :)
  • 能把代码的大纲显示一下吗?

标签: java sorting datetime


【解决方案1】:

因为你列表中的对象实现了Comparable接口,所以可以使用

Collections.sort(list);

其中list 是您的ArrayList


相关的 Javadocs:


编辑:如果您想以类似的方式对包含DateTime 字段的自定义类列表进行排序,则必须自己实现Comparable 接口。例如,

public class Profile implements Comparable<Profile> { 
    DateTime date;
    double age; 
    int id; 

    ...

    @Override
    public int compareTo(Profile other) {
        return date.compareTo(other.getDate());  // compare by date
    }
}

现在,如果您有 ListProfile 实例,则可以使用与上述相同的方法,即 Collections.sort(list) 其中 listProfiles 的列表。

【讨论】:

  • 如果 ArrayList 包含类 Profile public Profile{ DateTime date; 的对象怎么办?双倍年龄;内部标识; } 如何按日期排序?
  • Profile 是一个类,我自己写的
【解决方案2】:

DateTime 已经实现了 Comparable 你只需要使用Collections.sort()

【讨论】:

  • 如果 ArrayList 包含类 Profile public Profile{ DateTime date; 的对象怎么办?双倍年龄;内部标识; } 如何按日期排序?
  • 这种情况下需要实现自定义比较器
  • @Stas0n 在我的帖子中查看编辑
  • 你能展示一下代码的草图吗?
猜你喜欢
  • 2016-07-12
  • 2013-02-08
  • 2019-10-05
  • 1970-01-01
  • 2012-08-05
  • 2013-07-05
  • 2016-08-28
  • 2021-03-24
  • 2014-04-14
相关资源
最近更新 更多