【Java】ArrayList 存储学生并使用Collections比较排序

package LearnJava7;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

public class CollectionsDemo2 {
    public static void main(String[] args) {
        ArrayList<Student> array=new ArrayList<Student>();

        Student s1=new Student("xiaoA",21);
        Student s2=new Student("xiaoB",22);
        Student s3=new Student("xiaoC",23);
        Student s4=new Student("xiaoD",21);

        array.add(s1);
        array.add(s2);
        array.add(s3);
        array.add(s4);
//使用比较器排序
        Collections.sort(array, new Comparator<Student>() {
            @Override
            public int compare(Student s1, Student s2) {
//                按照年龄从小到大排列,年龄相同,按姓名排序
                int num = s1.getAge() - s2.getAge();
                int num2 = num == 0 ? s1.getName().compareTo(s2.getName()):num;
                return num2;
            }
        });
        for (Student s:array){
            System.out.println(s.getName()+","+s.getAge());
        }
    }
}

posted @   木子欢儿  阅读(58)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
历史上的今天:
2020-04-14 【网站建设】简单一行代码,为网站开启深色模式支持
点击右上角即可分享
微信分享提示
主题色彩