Java重写sort排序
2018-11-25 本文已影响42人
07120665a058
- 实现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);
}
}
- 在sort方面里面重写compare方法
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());
}
});