- 实现Comparable接口,重写compareTo()方法
public class Person implements Comparable<Person>{
private Integer age;
private String name;
public Person(Integer age, String name) {
this.age = age;
this.name = name;
}
@Override
public int compareTo(Person person) {
int compareAge = age.compareTo(person.age);
if(compareAge != 0){
return compareAge;
}
return name.compareTo(person.name);
}
}
list.sort(new Comparator<Person>() {
@Override
public int compare(Person person1, Person person2) {
int age = person1.getAge().compareTo(person2.getAge());
if (age != 0) {
return age;
}
return person1.getName().compareTo(person2.getName());
}
});