像这样创建一个类:
public class Person implements Comparable<Person> {
private String name;
private Date date;
public Person(String name, Date date) {
this.name = name;
this.date = date;
}
public String getName() {
return name;
}
public Date getDate() {
return date;
}
@Override
public int compareTo(Person o) {
return this.date.compareTo(o.getDate());
}
}
然后你可以Person
像这样对对象列表进行排序:
public static void main(String... args) {
LinkedList<Person> persons = new LinkedList<Person>();
persons.add(new Person("Name1", new Date())); //Specify different dates
persons.add(new Person("Name2", new Date()));
persons.add(new Person("Name3", new Date()));
Collections.sort(persons);
//Collections.sort(persons, Collections.reverseOrder()); //Reverse order
}
而已。
或者另一种选择是使用Comparator
:
Collections.sort(persons, new Comparator<Person>() {
@Override
public int compare(Person o1, Person o2) {
return o1.getDate().compareTo(o2.getDate());
}
});
相反的顺序:
Collections.sort(persons, Collections.reverseOrder(new Comparator<Person>() {
@Override
public int compare(Person o1, Person o2) {
return o1.getDate().compareTo(o2.getDate());
}
}));
然后你不需要Comparable<Person>
在你的 person 类中实现。