先按成绩由高到低,相等则按年龄由低到高

本文介绍了一个Java程序示例,该示例中定义了一个实现了Comparable接口的Student类,并通过重写compareTo方法实现了根据成绩和年龄进行排序的功能。程序展示了如何使用Arrays.sort方法对Student对象数组进行排序。

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

class Studentx implements Comparable<Studentx> {
    private String name;
    private int age;
    private float score;

    public Studentx(String name, int age, float score) {
        this.name = name;
        this.age = age;
        this.score = score;
    }

    public String toString() {
        return "Studentx [name=" + name + ", age=" + age + ", score=" + score
                + "]";
    }

    public int compareTo(Studentx o) {
        if (this.score > o.score) {
            return -1;
        } else if (this.score < o.score) {
            return 1;
        } else {
            if (this.age > o.age) {
                return 1;
            } else {
                return 0;
            }
        }
    }

}

public class ComparableDemo01 {
    public static void main(String[] args) {
        Studentx studentx[] = { new Studentx("von", 20, 90.0f),
                new Studentx("korea", 24, 92.0f),
                new Studentx("susan", 18, 90.0f),
                new Studentx("lily", 30, 92.0f),
                new Studentx("boy", 28, 84.2f), new Studentx("cais", 23, 97.3f) };
        java.util.Arrays.sort(studentx);
        for (int i = 0; i < studentx.length; i++) {
            System.out.println(studentx[i]);
        }
    }
}

转载于:https://www.cnblogs.com/vonk/p/3912473.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值