学生对象特定排序,比较器的实现

本文详细讲解了如何使用Java集合框架ArrayList存储学生对象,并实现按年龄和姓名排序的功能,涉及Comparator接口的使用和自定义比较器。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 			 Hello,大家好!我是Cx_330
本篇博文向大家演示一下如何通过集合创建并存储学生类
对象并且对学生类里面的相关信息进行特定的排序

题目描述

  • 用ArrayList存储学生对象,并且按照年龄从小到大进行排序,年龄相同时,按照姓名的字母顺序排序

考察知识

  • 通过Collections类对集合进行相关操作

  • 根据特定的需求自己实现一个比较器方法[Comparator<>]

  • 通过增强型for循环快速遍历ArrayList

源码实现

学生类源码
//首先创建一个学生类
//包括:构造方法  get/set
public class Student {

    private String name;
    private int age;

    public Student() {
    }

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}
存储排序学生对象源码
public class Test {
    public static void main(String[] args) {

        ArrayList<Student> arrayList = new ArrayList<Student>();
        Student student = new Student("keke",20);
        Student student1 = new Student("dingding",19);
        Student student2 = new Student("huihui",18);
        Student student3 = new Student("chengcehng",18);
        arrayList.add(student);
        arrayList.add(student1);
        arrayList.add(student2);
        arrayList.add(student3);
        Collections.sort(arrayList, new Comparator<Student>() {//自定义排序是解题的关键
            @Override//因为arrayList中存储的是学生类,不能直接简单调用sort,需要自己构建一个比较器实现排序
            public int compare(Student o1, Student o2) {
                int num1=o1.getAge()-o2.getAge();
                int num2=num1==0?o1.getName().compareTo(o2.getName()):num1;
                return num2;
            }
        });
        for (Student s : arrayList) {
            System.out.println(s.getName()+" "+s.getAge());
        }
    }
}

小结

  • 本例主要考察我们对**比较器**的创建应用,要学会在对类对象进行排序的时候根据特定的需求,逐条分析,然后有主次的创建自己的比较器
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

C_x_330

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值