创建这样一个类的自定义比较:
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>
。
有对象实现可比''和提供自己的'compareTo'实施 –
mre
[这](一个O(n)的更好的运行时间http://stackoverflow.com/questions/12817616/sort-a-list-based-on-a-parameter-available-in-another-class/12817959#12817959)答案可以使用。 – ReyCharles