Java的Comparable接口&比较器原理

对需要进行排序的对象实现Comparable接口,重写其中的compareTo(T o)方法,在其中定义排序规则,那么就可以直接调用java.util.Arrays.sort()来排序对象数组
需求:设计一个学生类, 属性有姓名,年龄, 成绩,并产生一个数组,要去安装成绩从高到低,如果成绩相等则有年龄有第到高排序。

import java.util.Arrays;
class Student implements Comparable<Student>{
    private String name;
    private int age;
    private float score;
    public Student(String name, int age, float score) {
        this.name = name;
        this.age = age;
        this.score = score;
    }
    public String toString() {
        return name + " " + age + " " + score;
    }
    public int compareTo(Student stu) {
        if(this.score > stu.score)  {
            return -1;
        } else if(this.score < stu.score) {
            return 1;
        } else {
            if(this.age > stu.age) {
                return 1;
            } else if(this.age < stu.age) {
                return -1;
            } else {
                return 0;
            }
        }
    }
}

public class ComparableDemo {
    public static void main(String[] args) {
        Student students[] = {new Student("张三", 20, 90.0f), new Student("李四", 22, 90.0f),
                new Student("王五", 20, 99.0f), new Student("赵六", 20, 70.0f), new Student("孙七", 22, 100.0f)};
        Arrays.sort(students);
        for (Student stu: students) {
            System.out.println(stu);
        }
    }

}

下面是Arrays类一些方法的demo, 点击Arrays类查看其方法的声明.

public class ArraysDemo {
    public static void main(String[] args) {
        int temp[] = {3, 5, 7, 9, 1, 2, 6, 8};
        Arrays.sort(temp);
        System.out.print("排序后的结果:");
        System.out.println(Arrays.toString(temp));
        int point = Arrays.binarySearch(temp, 3); 
        System.out.println("元素3的位置在: " + point);
        Arrays.fill(temp, 0);
        System.out.println("数组填充:" + Arrays.toString(temp));

    }
}
  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值