- public class Test {
- public static void main(String[] args) {
- List<Student> list = new ArrayList<Student>();
- //创建3个学生对象,年龄分别是20、19、21,并将他们依次放入List中
- Student s1 = new Student();
- s1.setAge(20);
- Student s2 = new Student();
- s2.setAge(19);
- Student s3 = new Student();
- s3.setAge(21);
- list.add(s1);
- list.add(s2);
- list.add(s3);
- Collections.sort(list, new Comparator<Student>(){
- /*
- * int compare(Student o1, Student o2) 返回一个基本类型的整型,
- * 返回负数表示:o1 小于o2,
- * 返回0 表示:o1和o2相等,
- * 返回正数表示:o1大于o2。
- */
- public int compare(Student o1, Student o2) {
- //按照学生的年龄进行升序排列
- if(o1.getAge() > o2.getAge()){
- return 1;
- }
- if(o1.getAge() == o2.getAge()){
- return 0;
- }
- return -1;
- }
- });
- System.out.println(“排序后:”+list);
- }
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。