Java如何给数组排序Comparable方式

通过Comparable接口实现类的自定义排序

简介:通过给类继承接口的方式来 重写compareTo方法 然后自定义排序规则,在合作开发的过程中 每个人更能很好的负责自己模块,提高开发效率。

import java.util.Arrays;
import java.util.Comparator;

public class Main {
    // 通过给类继承接口的方式来 重写compareTo方法 然后自定义排序规则
    static class Student implements Comparable<Student>{
        public int age;
        public String name;

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

        // 重写toString方法方便显示
        @Override
        public String toString() {
            return "Student{" +
                    "age=" + age +
                    ", name='" + name + '\'' +
                    '}';
        }

        // 这样的好处在于 在合作开发的过程中 每个人更能很好的负责自己模块
        @Override
        public int compareTo(Student o) {
            // compareTo方法比较原理在于用本类的this对象与 传入的o对象之间进行比较
            int num = 0;
            if (this.age >= o.age) num = -1;
            else num = 1;
            return num;
        }
    }

    public static void main(String[] args) {
        // 对于普通数组的排序
        Student [] a= new Student [5];
        a[0] = new Student(10, "李华");
        a[1] = new Student(9, "李明");
        a[2] = new Student(12, "李肖");
        a[3] = new Student(1, "李大");
        a[4] = new Student(5, "李页");


        // 对Student类按照年龄升序排序 可以不传入比较方法
        Arrays.sort(a);
        for (int i = 0; i < a.length; i++) {
            System.out.print(a[i] + " ");
        }
        // Student{age=12, name='李肖'} Student{age=10, name='李华'} Student{age=9, name='李明'} Student{age=5, name='李页'} Student{age=1, name='李大'}
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

极客李华

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

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

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

打赏作者

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

抵扣说明:

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

余额充值