如何排序ArrayLists?

Sta*_*s0n -2 java sorting datetime

我有一些列表包含DataTime类型的元素(Joda-time).我怎样才能按日期对它们进行排序?如果有人给出了这个例子的链接,那将会很棒......

ars*_*jii 8

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

Collections.sort(list);
Run Code Online (Sandbox Code Playgroud)

这里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
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,如果你有一个ListProfile情况下,你可以使用同样的方法如上,即Collections.sort(list)这里list是列表Profile秒.


Jig*_*shi 6

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