如何在java中使用Collections.sort()?

Mik*_*hin -2 java sorting collections list

我有一个简单的类 - 人.

public class Person {
    private int age;

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

    public int GetAge() {
        return age;
    }
}
Run Code Online (Sandbox Code Playgroud)

我提出了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();
            }
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

duf*_*ymo 5

你的比较者错了.试试这个:

 public int compare(Person a1, Person a2) {
     return a1.getAge().compareTo(a2.getAge());      
 }
Run Code Online (Sandbox Code Playgroud)

要么

 public int compare(Person a1, Person a2) {
     return (a1.getAge() - a2.getAge());      
 }
Run Code Online (Sandbox Code Playgroud)

想想比较者的合同.它返回一个int,而不是boolean.