案例:ArrayList存储学生对象并排序

 

 

public class CollectionsDemo {
    public static void main(String[] args) {
        //创建集合对象
        ArrayList<Student> arrayList = new ArrayList<Student>();

        //创建学生对象
        Student s1 = new Student("linqingxia",30);
        Student s2 = new Student("zhangmanyu",35);
        Student s3 = new Student("wangzuxian",33);
        Student s4 = new Student("liuyan",33);

        //把学生添加到集合
        arrayList.add(s1);
        arrayList.add(s2);
        arrayList.add(s3);
        arrayList.add(s4);

        //使用Collections对ArrayList集合排序
        //sort(List<T> list, Comparator<? super T> c) 根据指定的比较器引起的顺序对指定的列表进行排序。
        Collections.sort(arrayList, new Comparator<Student>() {
            @Override
            public int compare(Student s1, Student s2) { //形参s1的实参为第二个对象-->s2 所以下面是35-30 = 5
                int num = s1.getAge() - s2.getAge();
                int num2 = num==0?s1.getName().compareTo(s2.getName()):num;
                return num2;
            }
        });

        //遍历集合
        for (Student s : arrayList){
            System.out.println(s.getName()+","+s.getAge());
        }
    }
}

运行结果:

 

posted @ 2020-04-13 12:39  硬盘红了  阅读(584)  评论(0编辑  收藏  举报