Java重写sort排序

2018-11-25  本文已影响42人  07120665a058
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());
           }
});
上一篇下一篇

猜你喜欢

热点阅读