java - 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();
}
});
}
}
解决方案
您的比较器是错误的。尝试这个:
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 的合同。它返回一个整数,而不是布尔值。
推荐阅读
- python - 如何在 Tensorflow 中替换二维张量中的某些行
- spring-boot - 从哪个版本的 JHipster,Okta 集成是可能的?
- python-3.x - 循环读取多个文件
- angular - 无法访问 Angular 父组件中的 @ViewChild 属性
- python-3.x - 对于我的脚本中无法实现的每一行“for循环”
- python - 循环使用 lambda 列并使用其他列的值进行计算
- jprofiler - 监控 JProfiler 的许可证服务器
- vue.js - 如何在vuejs的子组件中将值从prrent传递到方括号
- ios - 从 nib 文件加载视图时出现问题,视图宽度为 0.0
- flutter - 我怎样才能摆脱这种颤振覆盖错误?