ArrayList排序方式-使用Collections工具类

该博客展示了如何使一个ArrayList中的对象(此处为Student类)实现Comparable接口,从而能够使用Collections.sort()方法进行排序。博客中创建了Student类,包含姓名和成绩属性,并实现了compareTo()方法基于成绩比较。然后创建了一个ArrayList<Student>并添加了几个Student实例,最后通过Collections.sort()按成绩对列表进行排序并打印结果。

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

让ArrayList内存放的对象类实现Collections接口

public class Student implements Comparable<Student> {
    String name;
    int grade;

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

    @Override
    public int compareTo(Student o) {
        return this.grade-o.grade;
    }
}
import java.util.ArrayList;
import java.util.Collections;

public class Team {
    static ArrayList<Student> student=new ArrayList<>();

    public static void main(String[] args) {
        Student x1=new Student("李隆会",59);
        Student x2=new Student("张晨羊",80);
        Student x3=new Student("肖泽融",60);
        Student x4=new Student("李佳博",100);

        student.add(x1);
        student.add(x2);
        student.add(x3);
        student.add(x4);

        Collections.sort(student);

        for(Student s : student){
            System.out.println(s.name+s.grade);
        }

    }
}

运行结果:

李隆会59
肖泽融60
张晨羊80
李佳博100

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值