首页 > 解决方案 > java中如何使用Collections.sort()?

问题描述

我有一个简单的类 - 人。

public class Person {
    private int age;

    public Person(int age) {
        this.age = age;
    }

    public int GetAge() {
        return age;
    }
}

我阅读了 10 到 20 岁的人名单。现在,我想使用 Collections.sort() 方法对列表进行排序,但我不明白这是如何工作的。

public class Main {
    public static void main (String [] args) throws IOException {
        List<Person> list = new ArrayList<Person>();
        list.add(new Person (11));
        list.add(new Person (13));
        list.add(new Person (32));
        list.add(new Person (10));

        Collections.sort(list, new Comparator <Person>() {
            @Override
            public int compare(Person a1, Person a2) {
                return a1.GetAge() > a2.GetAge();
            }
        });
    }
}

标签: javalistsortingcollections

解决方案


您的比较器是错误的。尝试这个:

 public int compare(Person a1, Person a2) {
     return a1.getAge().compareTo(a2.getAge());      
 }

或者

 public int compare(Person a1, Person a2) {
     return (a1.getAge() - a2.getAge());      
 }

想想 Comparator 的合同。它返回一个整数,而不是布尔值。


推荐阅读