美文网首页
Java重写sort排序

Java重写sort排序

作者: 07120665a058 | 来源:发表于2018-11-25 14:56 被阅读42次
    • 实现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());
               }
    });
    

    相关文章

      网友评论

          本文标题:Java重写sort排序

          本文链接:https://www.haomeiwen.com/subject/guognftx.html