s-day03--比较器Comparetor的使用

This commit is contained in:
xx
2026-10-15 10:24:22 +08:00
parent 196c293950
commit 2769b710a6
@@ -31,5 +31,25 @@ public class Demo14 {
});
System.out.println(lists);
//请大家创建一个保存学生对象的集合,并按学生的年龄升序排序,要求使用比较器
ArrayList<Student> students = new ArrayList<>();
Collections.addAll(students
, new Student("张三1", 19)
, new Student("张三2", 20)
, new Student("张三3", 18)
, new Student("张三4", 21)
);
System.out.println(students);
//希望集合的学生按年龄排序(升序,降序)
Collections.sort(students);
System.out.println(students);
//使用比较器对学生,按年龄升序排序(比较器)
Collections.sort(students, new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
return o1.age-o2.age;
}
});
System.out.println(students);
}
}