Java重写sort排序

  • 实现Comparable接口,重写compareTo()方法
public class Person implements Comparable{
    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() {
           @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());
           }
});

你可能感兴趣的:(Java重写sort排序)