如何在java中使用Collections.sort()?
我有一个简单的班上人如何在java中使用Collections.sort()?,java,list,sorting,collections,Java,List,Sorting,Collections,我有一个简单的班上人 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 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();
}
});
}
}
公共类主{
公共静态void main(字符串[]args)引发IOException{
列表=新的ArrayList();
增加(新人员(11));
增加(新人员(13));
列表。添加(新人员(32));
增加(新增人员(10人));
Collections.sort(列表、新比较器(){
@凌驾
公共整数比较(人员a1、人员a2){
返回a1.GetAge()>a2.GetAge();
}
});
}
}
通常,在compare()函数的@Override实现中,您需要返回-1、0或1(通常是int)的内容。所以,在这种情况下,你会想要这样的东西:
@Override
public int compare(Person a1, Person a2) {
return a1.GetAge().compareTo(a2.GetAge());
}
这将根据年龄对人员a1和人员a2进行订购。根据您想要的顺序(升序与降序),您可以按a2.GetAge().compareTo(a1.GetAge())进行比较;这也很好
你还需要考虑两个值相等的情况(当你返回0时)。
< P>你的比较器是错误的。试试这个: public int compare(Person a1, Person a2) {
return a1.getAge().compareTo(a2.getAge());
}
或
考虑一下比较器的合同。它返回一个int,而不是boolean。你不明白什么?这根本不起作用。它编译了吗?compare应该返回int,而不是像您的例子中那样的布尔值。不,它不会编译
a1.GetAge()>a2.GetAge()
返回一个布尔值@MikhailDedyukhin看到了duffymo的答案。@Snoob或者你可以:Collections.sort(list,Comparator.comparating(Person::GetAge))代码>使用Integer.compare(…,…)会更清楚这是一个意见问题。我将重点了解该方法返回的内容。如果你知道,任何一个都是清楚的。
public int compare(Person a1, Person a2) {
return (a1.getAge() - a2.getAge());
}